# Why isn't it ending? [closed]

Your task: To write a program that should obviously terminate, but it never (to the extent of a computer crash) does. Make it look like it should perform a simple task: adding numbers, printing something,... But it just gets caught in an infinite loop.

Try to make your program very clear and simple, while it actually will get stuck in an unforeseen loop. Voters: judge the answers on how "underhanded" they are!

This is a popularity contest: Be creative!

• Could someone please explain what I can do to make the question less broad? I am new here. Thank you! – Number9 Mar 16 '14 at 13:58
• This is just going to be a big list of typos and beginner's mistakes which cause loops. – Bill Woodger Mar 17 '14 at 0:51
• Interesting question, but I haven't seen any truly creative answers yet. I promise up votes to anyone who doesn't use loops or obvious recursion! – ApproachingDarknessFish Mar 17 '14 at 5:35
• I don't know if this counts, but my Microsoft Office is behaving exactly like this at the moment. – Level River St Mar 22 '14 at 11:40
• I'm voting to close this question as off-topic because underhanded challenges are no-longer on-topic here. meta.codegolf.stackexchange.com/a/8326/20469 – cat Apr 15 '16 at 14:20

## Javascript

This once bit me years ago:

function outerloop(){
for(i=0;i<10;i++){
innerloop();
}
}
function innerloop(){
for(i=0;i<5;i++){
console.log(i)
}
}
outerloop();


The trick here is that when one uses for( i=0 ..., the variable i is created in the global scope (even if they're in separate functions), so it gets overwritten every time by the inner loop. This is an easy pitfall for those coming from C++ or PHP. The fix is to use var to declare the variable in local scope (for (var i...)

PowerShell

$i = 1 do {$i++

# Java

Spawns a thread that will sleep for 1 second. The program should effectively sleep for a second while waiting for that thread to quit, and then end.

import java.lang.*;

class A {
static boolean done;
public static void main(String args[]) {
done = false;
public void run() {
try {
} catch (Exception e) {
done = true;
}
done = true;
}
}.start();
while (!done);
System.out.println("bye");
}
}


Why it doesn't end

• nice quirk :P; there are always some of them in each language – masterX244 Mar 19 '14 at 20:37
• Though depending on your VM this might work just as expected. – Paŭlo Ebermann Mar 24 '14 at 11:31

# JavaScript

while(true)
if(NaN == NaN)
break;
else
console.log("Batman");


A funny property of the global NaN (Not a Number) object in JavaScript is that it is not equal to itsself. To test if a number is NaN one must use isNaN(). It's also amusing that typeof(NaN) returns "number".

• The behaviour is actually part of the IEEE754 spec for floating point behaviour, which is used in many languages (C++, Java, .Net, etc) and is the usual way to represent floating point numbers in binary. Javascript uses dynamic typing, so a variable can contain a numeric value, a string value or an object reference (e.g. an array). A NaN is still a numeric type of value, which is why its type is Number - it's not an empty string or a Null object. – Phil H Dec 17 '14 at 16:26
• It's kind of funny that the type of NaN is actually number. – hetzi Dec 17 '14 at 16:28

## C

This prints numbers from 0 to 9. Or at least it should...

#include <stdio.h>

int main() {
int i;
char line[12]; // "Iteration: x"

for(i = 0; i < 10; i++) {
sprintf(line, "Iteration: %d", i);
puts(line);
}

return 0;
}


This is a classic off-by-one error triggering a stack overflow. The string is indeed 12 characters long, but the programmer forgot about the NULL terminator inserted by sprintf! On GCC, local variables are pushed to the stack in declaration order. Other compilers may order the variables differently. Since the stack grows backwards, this means i is after line in memory. The null byte overwrites the least significant byte of i. At the end of the block, i is always 0. i is incremented and it loops forever with i = 1.

## C

int main(void)
{
float count = 0;
while(count < 33554432L)
{
count++;
}
return 0;
}


Floating-point numbers have limited precision. Under IEEE 754 floating-point math, a single-precision float only has 24 bits of precision: the largest integer that can be represented exactly is 16,777,216. 16777216 + 1 = 16777216.

• Not, in fact, true in either theory or practice. Clause 5.2.4.2.2 of the C standard says that the accuracy of these floating point operations is implementation-defined, and implementations are furthermore allowed to evaluate float arithmetic using double or even long double precision. Clause 5.1.2.3 allows implementations to omit unneeded side-effects. The clang compiler, with optimization turned on, does exactly this. It optimizes away the entire loop and the loop control variable, yielding a program that terminates with return 0. The emitted (x86) machine code is 2 instructions. – JdeBP Mar 18 '14 at 14:48
• Moreover, if the loop doesn't have any side effects (like here where the count variable isn't used), compiler may assume that loop does terminate. – Ruslan Mar 19 '14 at 9:20
• @JdeBP C requires assignments and casts to drop any excess precision, and no matter what precision float has on a particular implementation, there will be some value for which adding 1 has no effect. 5.2.4.2.2p8: "Except for assignment and cast (which remove all extra range and precision), the values of operations with floating operands and values subject to the usual arithmetic conversions and of floating constants are evaluated to a format whose range and precision may be greater than required by the type." Ruslan's comment seems like the only reason it can terminate. – hvd Mar 19 '14 at 23:48
• Too many float related answers! – Anonymous Pi Mar 21 '14 at 2:07
• Ruslan's comment is a restatement of what I said, where I explicitly pointed to clause 5.1.2.3. Compilers don't solve the halting problem. They eliminate code with unneeded side effects. Here, they recognize a canonical iteration statement with a non-constant controlling expression and no needed side-effects (nor synchronization operations), and eliminate it. Clause 6.8.5 explains how. – JdeBP Mar 22 '14 at 8:59

## C#

Perhaps too obvious, but

class Program
{
static void Main()
{
int x = 0;
while (x * x != 1000)
x++;
System.Console.WriteLine("Square root of 1000 is " + x);
}
}


The square root of 1000 is not an integer, so it will never find it. It's just going to loop forever, assuming overflows aren't checked (the default is unchecked). So like I said, perhaps too obvious. But when I first saw it, I was pretty sure it was going to terminate - 1000 looks as though it should have an integer square root - to me, anyway.

Postscript

hello.ps:

/hello
{
(Hello, world\n) print
quit
}
dup 2 3 index cvx put def

hello


This prints "Hello, world" forever. To try it with ghostscript:

gs -sDEVICE=nullpage hello.ps


dup 2 3 index cvx put replaces the procedure's call to quit with a recursive call to procedure hello. Since postscript does tail call optimization, this runs forever without overflowing the stack.

## TeX (Plain): Typesetting The Song That Never Ends

Compile with pdftex. It is not obfuscated (besides, well, being written in TeX) and actually does end, as pdftex stops after somewhat about 2.6 million pages...

\font\bigrm=cmr12 at 14pt
\centerline{\bigrm The Song That Never Ends}
\bigskip
\def\songthatneverend{
\noindent This is the song that never ends.\hfil\break
Yes, it goes on and on my friends.\hfil\break
Some people started singing it not knowing what it was,\hfil\break
and they'll continue singing it forever just because\smallskip

\expandafter\songthatneverend}
\songthatneverend
\bye

• Hmm, this is not that underhanded, I would say. – Paŭlo Ebermann May 31 '14 at 23:01
• @PaŭloEbermann: No it isn't. It is just TeX :-) – Daniel Jun 3 '14 at 11:20

# Ruby

if p
//misses
raise 'Unreachable'
end

while p //nonsense, Kernel#p always returns nil, which is falsey, so this will immediately terminate.
puts 'Looping'
end

puts 'Done looping'


### Batch

This loops forever outputting Hello.

@echo off
for /l %%a in (0,0,1) do echo Hello.


The for loop tries to count from 0 to 0 incrementing by 1 - (0,0,1). So it never reaches zero.

Or if you want to cause the prompt to crash.

@echo off
for /l %%a in (0,1,1) do call %%%%a
:1
echo END


--

h:\uprof>end.bat
******  B A T C H   R E C U R S I O N  exceeds STACK limits ******
Recursion Count=477, Stack Usage=90 percent
******       B A T C H   PROCESSING IS   A B O R T E D      ******


# Javascript

Here's a typical beginner's programming exercise.

Continually repeat a sequence of 1..n1, until you've output a total of n2 numbers. For example, looping through 1..3 where the total quantity is 10 would produce this:

1 2 3 1 2 3 1 2 3 1

Below is a solution that uses a currying function. It's simple, elegant, and will hang your browser :-)

function output(msg) {
$('<span></span>').text(msg).appendTo($('#output'));
}

function loopThroughSequence(max) {
i = 0;
return function() {
if(i >= max) {
i = 0;
}
return ++i;
}
}

var getNextInSequence = loopThroughSequence(3);
for(var i = 0; i < 10; ++i) {
output(' ' + getNextInSequence());
}


Note that loopThroughSequence forgets to declare i in scope. (It needed to preceed 'i' with the 'var' keyword.) Instead, it uses the i value declared below it in the for loop, and continually resets it back to zero.

• A function that returns another function ... it ain't that simple. And the double loop "i" has been posted by @Aleksi Torhamo – rafaelcastrocouto Mar 20 '14 at 19:11

C++

#include<fstream.h>
int main()
{
char ch[80];
ifstream fin("evil.txt");
while(fin)
{
fin.get(ch,50); //read by lines
cout<<ch;
} //nothing wrong, right? wrong.
return 0;
}


evil.txt contains following data :

hello.
I am awesome.


fin.get() leaves a '\n' in input stream. The rest is Elementary, my dear.

#include<stdio.h>

void main(){
while((10*5/3)!=(10/3*5))
printf("In a loop\n");
}


Mathematically (10/3)*5==(10*5)/3;

• You can omit the parentheses, and even use the same type for both a and b. But it is still quite obvious where the problem is, you should hide it in some piece of program which seems to be useful. – Paŭlo Ebermann Mar 24 '14 at 11:09

This is just a simple program to illustrate return statements. Since the return statement ends the function, it doesn't run anything after it.

sayHello :: IO String
sayHello = do
return "Hello!"
sayHello

main = do
hello <- sayHello
putStrLn hello


Return statements don't end functions, unlike in other languages.

Whitespace

(actual working code follows)

FSSSSSTTFFSFSSSSSTTFF
Where F is linefeed, S is space and T is tab

• The Stack Exchange platform doesn't support Whitespace. You may want to use normalized Whitespace, or paste the script on the platform that does support it. – Konrad Borowski Mar 23 '14 at 13:38
• The code is there when I try to edit but apparently does not render properly. In any case, it is more a positional answer that the OP's question can be (maybe best) answered using Whitespace. – Darrell Teague Mar 23 '14 at 14:19

c#

    public void MemoryEfficientCountTo256()
{
for (byte i = 0; i <= 255; i++)
{
Console.WriteLine(i);
}
}


This is from a stackoverflow question. A byte can never be 256, so adding one takes it back to 0

Java

public class Main {
public static void main(String[] args) {
try{
double i=1.0/0.0;
while(i==i+1){  //weired condition should never be true
System.out.println("This should never be printed");
}
}catch (ArithmeticException e){
System.out.println("Caught divide by 0 exception");

}
}
}

• The classic NaN :D – Silviu Burcea Mar 17 '14 at 12:51
• @SilviuBurcea Not a NaN (NaN != NaN), but an infinity. – Paŭlo Ebermann Mar 24 '14 at 12:03
• This should be hidden better. – Paŭlo Ebermann Mar 24 '14 at 12:03

C

int main(void) {
int x;
while(x<=10) x+=1;
}


from my experience this thing loops indefinitely only after 4 years of stable production at 3AM on a Saturday and once it loops for first time no system reboot can make it go away and within 15 minutes it happens to all high availability servers, dumping the entire production stack offline for a day.

• Why the downvote? This is a variation of a real deal, the int usually gets randomly allocated on a zero-padded memory segment, but just sometimes gets allocated where there's garbage already so incrementing never reaches 10 – bbozo Mar 17 '14 at 10:37
• Compilation fails due to missing (). – orion Mar 17 '14 at 10:45
• @bbozo it ought to reach 10 anyway, even if it starts with garbage, due to wraparound. – imallett Mar 17 '14 at 23:21
• @IanMallett: Not necessarily. Accessing an uninitialized non-static variable is undefined behavior. So is signed integer overflow. – Dennis Mar 18 '14 at 2:11
• – Dennis Mar 18 '14 at 2:20

## Ruby

This is a super efficient piece of code that simulates a dice.

def almost_dice
rand(7) # will output a number between 0 and 6.
end

#I want a dice that outputs a number between 1 and 6, so I have no other choice, right?
def proper_dice
d = almost_dice
while d = 0
d = almost_dice #Eventually, I'll get d != 0
end
return d
end

puts proper_dice


In ruby what could look like a test : d = 0 is actually an assignment. Since the assignement always succeed, then the test always returns true, hence the infinite loop

• Answer: i.stack.imgur.com/DDifD.png – Riking Mar 17 '14 at 17:54
• Same trick works the same way in C – Glenn Randers-Pehrson Mar 18 '14 at 3:23
• @GlennRanders-Pehrson no, in C the assignment would have the value 0 (which is falsy), so it wouldn't loop at all. – Paŭlo Ebermann Mar 24 '14 at 11:52
• @PaŭloEbermann Right, it's the same trick (mistaking "=" for "=="), but not exactly the same, as you said. – Glenn Randers-Pehrson Mar 24 '14 at 14:04

## C#

Let's take a page from this answer: https://codegolf.stackexchange.com/a/24376/16729 but do the computation on a background thread in the class constructor!

class BackgroundSummer
{
static int sum;
static BackgroundSummer()
{
// Let's compute the sum on another thread!
}

static void ComputeSum()
{ /* omitted: compute the sum here */ }

static void Main()
{ }
}


An explanation of why this runs forever is here: http://ericlippert.com/2013/01/31/the-no-lock-deadlock/

# Scala

var break = false
for(i <- Stream.from(0) if !break) {
break = i >= 10
}
println("Well done!")


Infinite streams will continue to be evaluated even if break is true.

Or the second one.

var g = 6
def counter: Int = {
g -= 2
g
}
def test() = {
val t = ListBuffer('s','t','a','r','t',' ','e','m','p','t','y')
var i = t mkString // returns "start empty"
var l = ListBuffer[Int]()
while(i != "42") i = (l += counter) mkString // returns "42 after two iterations"
s"$i should equal 42" } println(test())  mkString captures the second argument as a separator, here s"$i should equal 42". So the value of \$i is never "42" but goes indefinitely.

wxpython

"Hello World" example that fails to exit.

import sys
import time
import wx
from wx.lib.pubsub import setupkwargs
from wx.lib.pubsub import pub

class LoggerWindow(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Logger")
self._log = wx.TextCtrl(self, style=wx.TE_MULTILINE)
pub.subscribe(self.OnLogMessage, "LOG_MESSAGE")

def OnLogMessage(self, msg):
self._log.AppendText(msg)

class GUI(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Demo GUI - Hello World")
self._logger = LoggerWindow()
pub.sendMessage("LOG_MESSAGE", msg="GUI Starting")

# Set up the Hello World message
self._display = wx.TextCtrl(self, -1, size=(400,20), style=wx.TE_MULTILINE)
self._display.AppendText("Hello World!")

# Show it for a while
self.Show()
time.sleep(10)

# Done
self.Destroy()

App = wx.App()
Gui = GUI()
App.MainLoop()


The log window, while not showing, keeps existing, so the "GUI" window disappears but the app keeps running. I had intended for this to be another example of "not using a loop", but obviously I am using a loop!

## Python

def sum(first, add=[]):
sum = 0
for el in add:
sum+= el
print sum

if __name__ == '__main__':
#init
for el in add:
sum(el)


this will loop forever due to the fact that expressions in default arguments are calculated when the function is defined, not when it’s called. So the list will grow until the user terminate the script.

# JAVASCRIPT

found this while doing my project

function weirdCode(){
var myarray= ["test",123,false];
var myarray2 = myarray;
myarray2[2] = !myarray2[2];
while(myarray.toString() == myarray2.toString()){
console.log("shouldn't myarray[2] == false? but it is "+myarray[2]+". but i only edit myarray2, which is "+myarray2[2]);
}
console.log("this will never called");
}
weirdCode();


at line "var myarray2 = myarray;" it should be "var myarray2 = myarray.slice()", cause it will be referring the var to myarray, like sharing a var

• Another obvious one ... myarray2 = myarray makes it ease to see. – rafaelcastrocouto Mar 20 '14 at 19:01
• on some coding language, copying an array are 'var CopyOfAnArray = OriginalArray;' – wuiyang Mar 21 '14 at 16:36
• well .. not in js! – rafaelcastrocouto Mar 21 '14 at 16:51

## JAVASCRIPT

 var x = 1; while(x != 0) x -= 0.1;


x = 1;
x - 0.1 = 0.9;
x - 0.1 = 0.8;
x - 0.1 = 0.7000000000000001
WHAT!!!!!

Now more about it

## Java, equal but not?

import java.util.HashMap;
import java.util.Map;

public class Endless {
static class A {
public A(int a) {
b = a;
}

int b;
@Override
public boolean equals(Object obj) {
return obj != null && (obj instanceof A) && ((A)obj).b == b;
}
}

public static void main(String args[]) {
Map<A,String> map = new HashMap<A, String>();
A a = new A(1);
A sameA = new A(1);

System.out.println("a is sameA?" + a.equals( sameA ));

map.put(a, "look ma, no hands!");

while (!map.containsKey(sameA)){
//we never get here, do we?
}
System.out.println("Done!");
}
}

• While it is not obvious why the loop condition is true, it is quite clear that the problem must be there. I recommend hiding it better in a program piece which seems to do something useful. – Paŭlo Ebermann Mar 24 '14 at 11:12