93
votes
\$\begingroup\$

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!

\$\endgroup\$
11
  • 6
    \$\begingroup\$ Could someone please explain what I can do to make the question less broad? I am new here. Thank you! \$\endgroup\$
    – Number9
    Commented Mar 16, 2014 at 13:58
  • 6
    \$\begingroup\$ This is just going to be a big list of typos and beginner's mistakes which cause loops. \$\endgroup\$ Commented Mar 17, 2014 at 0:51
  • \$\begingroup\$ 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! \$\endgroup\$ Commented Mar 17, 2014 at 5:35
  • 14
    \$\begingroup\$ I don't know if this counts, but my Microsoft Office is behaving exactly like this at the moment. \$\endgroup\$ Commented Mar 22, 2014 at 11:40
  • 1
    \$\begingroup\$ 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 \$\endgroup\$
    – cat
    Commented Apr 15, 2016 at 14:20

73 Answers 73

4
votes
\$\begingroup\$

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...)

\$\endgroup\$
4
votes
\$\begingroup\$

PowerShell

$i = 1

do {
    $i++
} until( $i > 10 )

The > is not the greater-than operator (which is -gt); it is the redirection operator. Since nothing is returned, PowerShell evaluates the expression as false and continues.

\$\endgroup\$
3
votes
\$\begingroup\$

It is a GUI program that will show an empty frame titled Hello, world! and hide the frame in 1 second.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // Create a frame titled "Hello, world!".
                final JFrame frame = new JFrame("Hello, world!");
                frame.setVisible(true);

                // After 1 second...
                Timer timer = new Timer(1000, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        // Hide the frame.
                        frame.setVisible(false);
                    }
                });
                timer.setRepeats(false);
                timer.start();
            }
        });
    }
}

The frame is hidden, but it is not disposed, so the virtual machine would not terminate. Reference: http://docs.oracle.com/javase/7/docs/api/java/awt/doc-files/AWTThreadIssues.html#Autoshutdown

\$\endgroup\$
6
  • 5
    \$\begingroup\$ Anyone who has programmed in Swing enough will know this. \$\endgroup\$
    – Justin
    Commented Mar 17, 2014 at 1:43
  • 4
    \$\begingroup\$ @Quincunx I think your comment can be applied to all answer above. \$\endgroup\$ Commented Mar 17, 2014 at 2:15
  • \$\begingroup\$ I agree. However, this answer is obvious to anyone who has barely begun programming in Swing. Swing programmers learn to use frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);, and when that is forgotten, the application just doesn't close. This implies that something special is needed to close the frame, not just setting it as invisible. \$\endgroup\$
    – Justin
    Commented Mar 17, 2014 at 2:23
  • \$\begingroup\$ Speaking as someone who's never heard of Swing before: Why would anyone who has been programming for more than a few weeks think that making something invisible is the same as releasing it? \$\endgroup\$
    – alexis
    Commented Mar 23, 2014 at 18:34
  • \$\begingroup\$ @alexis I did, and I sometimes still forget to add setDefaultCloseOperation until I see my program is still running after closure. \$\endgroup\$ Commented Mar 24, 2014 at 0:28
3
votes
\$\begingroup\$

C

int main(void) {
  float x = 0;
  while(x != 1) x+=0.1;
}

lots of nooses for a C developer....

\$\endgroup\$
6
  • \$\begingroup\$ main should be main() \$\endgroup\$ Commented Mar 17, 2014 at 9:18
  • 1
    \$\begingroup\$ Also, this terminates perfectly. \$\endgroup\$
    – trion
    Commented Mar 17, 2014 at 11:17
  • \$\begingroup\$ @trion, updated answer, should hang now \$\endgroup\$
    – bbozo
    Commented Mar 17, 2014 at 12:24
  • 2
    \$\begingroup\$ It will hang on typical implementations, but for completeness: it will run successfully on implementations where FLT_RADIX is 10. A quick search brings up TIGCC as an example of such an implementation. \$\endgroup\$
    – hvd
    Commented Mar 17, 2014 at 15:17
  • 1
    \$\begingroup\$ I imagine you could find another value that would be wonky when FLT_RADIX is 10, like 1.0/3.0. \$\endgroup\$ Commented Mar 19, 2014 at 18:01
3
votes
\$\begingroup\$

C

This was tested on a 64 bit machine with gcc using the compiler flag -fomit-frame-pointer.

int main() {
    long x = (long)main;
    asm("sub %0,%%rsp"::"i"(sizeof(x)));
}

This makes the return address the address of main. Which makes an infinite loop. The assembly line is needed to not run out of stack.

\$\endgroup\$
1
  • \$\begingroup\$ Didn't get why it hangs until used -S with gcc. I took %0 as $0 and didn't understand why the asm line wasn't a nop. \$\endgroup\$
    – Ruslan
    Commented Mar 19, 2014 at 9:15
3
votes
\$\begingroup\$

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;
        new Thread() {
            public void run() {
            try {
                Thread.sleep(1000); // dummy work load
            } catch (Exception e) {
                done = true;
            }
            done = true;
            }
        }.start();
        while (!done);
        System.out.println("bye");
    }
}

Why it doesn't end

\$\endgroup\$
2
  • 1
    \$\begingroup\$ nice quirk :P; there are always some of them in each language \$\endgroup\$
    – masterX244
    Commented Mar 19, 2014 at 20:37
  • \$\begingroup\$ Though depending on your VM this might work just as expected. \$\endgroup\$ Commented Mar 24, 2014 at 11:31
3
votes
\$\begingroup\$

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".

\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$
    – Phil H
    Commented Dec 17, 2014 at 16:26
  • \$\begingroup\$ It's kind of funny that the type of NaN is actually number. \$\endgroup\$
    – hetzi
    Commented Dec 17, 2014 at 16:28
3
votes
\$\begingroup\$

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.

\$\endgroup\$
2
votes
\$\begingroup\$

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.

\$\endgroup\$
6
  • 6
    \$\begingroup\$ 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. \$\endgroup\$
    – JdeBP
    Commented Mar 18, 2014 at 14:48
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – Ruslan
    Commented Mar 19, 2014 at 9:20
  • \$\begingroup\$ @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. \$\endgroup\$
    – hvd
    Commented Mar 19, 2014 at 23:48
  • 1
    \$\begingroup\$ Too many float related answers! \$\endgroup\$ Commented Mar 21, 2014 at 2:07
  • \$\begingroup\$ 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. \$\endgroup\$
    – JdeBP
    Commented Mar 22, 2014 at 8:59
2
votes
\$\begingroup\$

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.

\$\endgroup\$
2
votes
\$\begingroup\$

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.

\$\endgroup\$
1
2
votes
\$\begingroup\$

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
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Hmm, this is not that underhanded, I would say. \$\endgroup\$ Commented May 31, 2014 at 23:01
  • \$\begingroup\$ @PaŭloEbermann: No it isn't. It is just TeX :-) \$\endgroup\$
    – Daniel
    Commented Jun 3, 2014 at 11:20
2
votes
\$\begingroup\$

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'
\$\endgroup\$
1
vote
\$\begingroup\$

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      ******
\$\endgroup\$
1
vote
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ A function that returns another function ... it ain't that simple. And the double loop "i" has been posted by @Aleksi Torhamo \$\endgroup\$
    – user15260
    Commented Mar 20, 2014 at 19:11
1
vote
\$\begingroup\$

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.

\$\endgroup\$
1
vote
\$\begingroup\$

How about this...

#include<stdio.h>

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

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

\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 24, 2014 at 11:09
1
vote
\$\begingroup\$

Haskell

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.

\$\endgroup\$
1
vote
\$\begingroup\$

Whitespace

(actual working code follows)

Readable version:

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

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – null
    Commented Mar 23, 2014 at 13:38
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 23, 2014 at 14:19
0
votes
\$\begingroup\$

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");

        }
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ The classic NaN :D \$\endgroup\$ Commented Mar 17, 2014 at 12:51
  • \$\begingroup\$ @SilviuBurcea Not a NaN (NaN != NaN), but an infinity. \$\endgroup\$ Commented Mar 24, 2014 at 12:03
  • \$\begingroup\$ This should be hidden better. \$\endgroup\$ Commented Mar 24, 2014 at 12:03
0
votes
\$\begingroup\$

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.

\$\endgroup\$
7
  • \$\begingroup\$ 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 \$\endgroup\$
    – bbozo
    Commented Mar 17, 2014 at 10:37
  • 2
    \$\begingroup\$ Compilation fails due to missing (). \$\endgroup\$
    – orion
    Commented Mar 17, 2014 at 10:45
  • \$\begingroup\$ @bbozo it ought to reach 10 anyway, even if it starts with garbage, due to wraparound. \$\endgroup\$
    – geometrian
    Commented Mar 17, 2014 at 23:21
  • \$\begingroup\$ @IanMallett: Not necessarily. Accessing an uninitialized non-static variable is undefined behavior. So is signed integer overflow. \$\endgroup\$
    – Dennis
    Commented Mar 18, 2014 at 2:11
  • 2
    \$\begingroup\$ @IanMallett: Why does integer overflow on x86 with GCC cause an infinite loop? \$\endgroup\$
    – Dennis
    Commented Mar 18, 2014 at 2:20
0
votes
\$\begingroup\$

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

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

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!
    var thread = new System.Threading.Thread(ComputeSum);
    thread.Start();
    thread.Join();
  }

  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/

\$\endgroup\$
0
votes
\$\begingroup\$

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.

\$\endgroup\$
0
votes
\$\begingroup\$

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!

\$\endgroup\$
0
votes
\$\begingroup\$

Python

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

if __name__ == '__main__':
    #init
    add = sum(1)
    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.

\$\endgroup\$
0
votes
\$\begingroup\$

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

\$\endgroup\$
3
  • \$\begingroup\$ Another obvious one ... myarray2 = myarray makes it ease to see. \$\endgroup\$
    – user15260
    Commented Mar 20, 2014 at 19:01
  • \$\begingroup\$ on some coding language, copying an array are 'var CopyOfAnArray = OriginalArray;' \$\endgroup\$
    – wuiyang
    Commented Mar 21, 2014 at 16:36
  • \$\begingroup\$ well .. not in js! \$\endgroup\$
    – user15260
    Commented Mar 21, 2014 at 16:51
0
votes
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ Almost literally this answer codegolf.stackexchange.com/a/24386/16874 \$\endgroup\$
    – Milo
    Commented Mar 23, 2014 at 6:46
  • \$\begingroup\$ I usually only read JS answers ... you are 100% right, it's the same ... just different languages. \$\endgroup\$
    – user15260
    Commented Mar 23, 2014 at 10:48
0
votes
\$\begingroup\$

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!");
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$ Commented Mar 24, 2014 at 11:12
0
votes
\$\begingroup\$

How about a fork bomb?

:(){ :|: &};:
\$\endgroup\$
1
  • 2
    \$\begingroup\$ The ubiquitousness of the fork bomb makes this rather obviously non-terminating. \$\endgroup\$
    – ashastral
    Commented Mar 23, 2014 at 3:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.