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
    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\$ 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\$ 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\$ 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
    Apr 15, 2016 at 14:20

73 Answers 73

1 2
3
0
votes
\$\begingroup\$

Tcl

set i 1
while $i<=10 {
    puts $i
    incr i
}

I forgot to brace my expression, so $i will only be substituted once, when while is called

\$\endgroup\$
2
  • \$\begingroup\$ Also, no increment? \$\endgroup\$ Mar 24, 2014 at 11:27
  • \$\begingroup\$ Ohh, forgot the increment. Added. \$\endgroup\$ Mar 24, 2014 at 12:16
0
votes
\$\begingroup\$

C

This one works..

#include<stdio.h>

void main(){
double a=10;
float b=10;
while(a/3!=b/3)
printf("Infinite loop");
}
\$\endgroup\$
2
  • \$\begingroup\$ Can you add the language? \$\endgroup\$
    – Milo
    Mar 25, 2014 at 5:05
  • 1
    \$\begingroup\$ And similar things have been done already pertaining to floating point precision. \$\endgroup\$
    – Milo
    Mar 25, 2014 at 5:06
0
votes
\$\begingroup\$

Java

public class Looper {
    public static final int END = Integer.MAX_VALUE;
    public static final int START = END - 100;

    public static void main(String[] args) {
        int count = 0;
        for (int i = START; i <= END; i++)
            count++;
        System.out.println(count);
    }
}

This program was blatantly copied from Bloch and Gafter's Java Puzzlers.

The expression i <= Integer.MAX_VALUE is a tautology, at least if i is an int. By definition, no integer can be greater than Integer.MAX_VALUE.

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

In Ruby:

x = "a"

while ! x.equal?("aaaaaaaa")
   x += "a"
end

In Ruby, the .equal? method checks for object equality, not value equlity. "aaaaaaaa" is a unique object, and thus has a different object ID than x. Because of this the statement will never be true.

Another one:

a = b = "a"

while a == b
    b << "a"
end

Here a and b gets the reference to the same object. The << method actually changes the value at the location where the object is referencing, and does not create a new object as most other methods does. Since both a and b references the same location, the values will always be the same.

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

Powershell

I feel like counting from one to a hundred. Don't you?

$i = 1;
for($i -lt 100;$i++){$i}

...Wait a minute, that's way more than a hundred printing out...

...

...

This should be fairly simple to figure out, and I found it amusing, at least.

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

C

#include <stdio.h>

int count_bits(unsigned int field)
    {
    unsigned int a = 1;
    int count = 0;
    
    while (1)
        {
        switch (a)
            {
            case 1 << 31: /* MAX_UINT32 */
                {
                break;
                }
            default:
                {
                if (field & a) count++;
                a <<= 1;
                }
            }
        };
    return count;
    }

int main(int argc, char *argv[])
    {
    printf("%d\n", count_bits(0xdeadbeef));
    return 0;
    }

In C and C++ case is a jump target. The break breaks the switch, but not the while. Substituting break; with return count; will work.

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

Java, with OpenCV

(just a snippet)

VideoCapture camera = new VideoCapture(0);
Mat frame = new Mat();
while(frame.get(1, 1)[0]<200)camera.read(frame);

Java OpenCV stores pixel values from 0 to 1, not 0 to 255.

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

Lua

Totaly boring, but I thought it was still interesting:

-- Example of stack overflow using recursion
-- Function foo: this function will call itself forever: foo(foo(foo(foo(foo...
function foo() -- Our recursive function
    return foo() -- Our recursive call, this will cause the stack to overflow
end
pcall(foo) -- pcall will call foo in protected mode, catching stack overflows.
print("Stackoverflow! Avoid infinite recursion!") -- Use infinite recursion wisely

How does it work?

I dont have a clue. I think its optimized to something like:

call main
exit
label foo:
jmp foo
label main:
push foo
call pcall
push "Stackoverflow! Avoid infinite recursion!"
call print

Notes:

  • This is not assembly or lua bytecode or anthing
  • Exponential recursion will result in a stack overflow: foo(foo()). I think this is because this will call foo before it will jmp foo?
  • Can someone please make a C function and try it out with that? I would love to know if it will result in a overflow or not. (I am guessing it will, but you never know...)
\$\endgroup\$
0
votes
\$\begingroup\$

C++'s rules can be pesky some times

a.cpp:
#include "Shape.h" // includes class Shape, with virtual functions on it

int callback(int value, Shape* s)
{
    // aggregates areas
    return value + s->getArea();
}

// Some boring work... we don't even call this function
int aggrigateAreas(Shape* begin, Shape* end)
{
    int rval = 0;
    for (Shape* iter = begin; iter != end; iter++)
        rval = callback(rval, iter);
    return rval;
}


b.cpp:
#include "Shape.h"

int callback(Shape* s)
{
    // aggrigate perimieters
    return s->getPerimiter();
}

// doSomethingImportant will actually do something for us
int doSomethingImportant(Shape* s)
{
    return callback(s); // this was more complicated in real life
}

main.cpp
#include "Shape.h"
#include <iostream>
int doSomethingImportant(Shape* s);

int main() {
    Square s(1); // square with side length 1
    std::cout << doSomethingImportant(&s); // should print 4, right?
    return 0;
}

Sadly, C/C++ is rather unfriendly if you have two functions in different translation units with different names. They call it a ODR violation (One Definition Rule) and it's Undefined Behavior. As it so happens, if the linker is not being kind to you today, your call to callback in doSomethingImportant can end up calling the callback in a.cpp. This is bad enough, but they also don't have the same signatures. s may get some garbage value, such as something which causes the virtual function lookup of getArea() to return the address just before main, creating an infinite loop when called. It even gets a few broken opcodes just right to maladjust the stack back to its initials stack height, so you don't even get a sane stack overflow.

Is this against the rules of code golf? Maybe. I am trying to claim a win by getting very unlucky with a compiler's handling of undefined behavior. Technically that's outside of the spec of the language.

However, the scars I put into my cubicle walls that day, dug deep with my fingers as I screamed in agony remain. Dug over the course of that whole 12 hour work day, with the debugger taunting me as I went (You're {bleep}ing kidding me! Why did the debugger put me back in a.cpp again! I commented out all calls to that file wholesale! Maybe I should recompile the world again)... that has to qualify as "underhanded" somehow, right? Please?

I will not forget to open the anonymous namespace to store my callbacks

I will not forget to open the anonymous namespace to store my callbacks

I will not forget to open the anonymous namespace to store my callbacks

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

c++

A simple program, to show how operator overloading works:

EDIT: this is inspired by BF

#include <iostream>
class ops
{
public:
    int val=1;
    ops operator * (ops rhs){val++; return *this;}
    ops operator & (ops rhs){val-=3; return *this;}
};
int main() {
    ops a;
    while (a.val>0) 
    {
        a=a**&a; //call operator* twice and operator& once, net effect of subtracting 1
        std::cout<<a.val;
    }
    return 0;
}

This calls operator* once and operator& zero times. *&a is the same as a, because of pointers.

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

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

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

C#

   for (; ; )
    {
        try
        {
            string text = "SomeText";
            System.IO.File.WriteAllText(@"c:\Pathwith?.txt", text);

            break;
        }
        catch { }
    }
\$\endgroup\$
5
  • 1
    \$\begingroup\$ Well of course it doesn't terminate... why would it? \$\endgroup\$
    – orion
    Mar 17, 2014 at 11:01
  • \$\begingroup\$ Isn't this the purpose of the assignment? It should have ended if the file existed but it will throw exception and will never end \$\endgroup\$ Mar 17, 2014 at 11:03
  • \$\begingroup\$ It is, it's just not very surprising because it very obviously references a very particular file that most likely doesn't exist. \$\endgroup\$
    – orion
    Mar 17, 2014 at 11:17
  • \$\begingroup\$ Now is it better? \$\endgroup\$ Mar 17, 2014 at 12:20
  • \$\begingroup\$ Please be sure to include a language header with your answers, e.g. ## Java or ## C. Welcome to the site! \$\endgroup\$ Mar 17, 2014 at 12:26
-2
votes
\$\begingroup\$

C++ - Lame

Yay I is pro C++ I learnt for loop real quik now lets make cool program that print 1 to 10 cuz I am awesome and totaly did not chose C++ just cuz C doesnt allow for loop.

#include <stdio.h> // 2 lazy 4 std::cout

int main()
{
    int i = 1;
    for (i < 10; i++;)
    {
        printf("%d\n", i);
    }
}

No why I is pro C++ why U dont work I learn for syntax well :(

upvote @fuandon instead, he gave me the idea. This is my second one anyway...

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Clever trick. You might want to explain how it works in a spoiler. \$\endgroup\$
    – isaacg
    May 7, 2015 at 6:11
1 2
3

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