Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

This question already has an answer here:

Now that we have over a hundred ways to get stuck in a loop, the next challenge is to get out.

Specifically, write a piece of code with a (seemingly) infinite loop, but somehow manage to break out.

The "infinite loop" can be a statement like while true, for (;1>0;) or anything else which obviously lasts forever. Recursion does not count (since stack overflows will quickly occur).

To break out, you need to execute an instruction written just after the loop. You can not just exit the program or leave the method.

Valid answer (if only it somehow exited the loop):

while (true)
    print("I'm stuck!")

print("I escaped!")

Invalid answer:

define loop() {
    while (true)
        print("I'm stuck!")
}

loop()
print("I escaped!")
share|improve this question

marked as duplicate by Martin Büttner, Kyle Kanos, William Barbosa, Peter Taylor, DigitalTrauma Jul 21 at 21:01

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2  
I think this should be tagged with underhanded –  William Barbosa Jul 21 at 16:46
    
Are we allowed to use something such as break in python? You didn't seem to exactly specify that. –  DatEpicCoderGuyWhoPrograms Jul 21 at 18:02
    
@DatEpicCoderGuyWhoPrograms it is a popularity contents. My guess break wouldn't be very popular. –  Danny Jul 21 at 19:46
1  
I must be missing something, I don't understand how your "Valid answer" answers the question. How does the print statement break out of the loop? –  Greg Hewgill Jul 21 at 20:03
1  
why is this marked as duplicate? the questions are intirely different. for example, no answer for this question is a valid answer for the other question, nor any answer for the other question is valid here. –  proud haskeller Jul 21 at 21:39

7 Answers 7

GolfScript

"0:1 Argentina - Germany":party~
{party puts 1}do
"Party is over."

Try it online.

How it works

"0:1 Argentina - Germany" # Push party string.
:party                    # Save string in party variable.
~                         # Discard the string from the stack.
{                         #
  party                   # Push party string.
  puts                    # Print string followed by a newline.
  1                       # Push a truthy conditional on the stack.
}do                       # Pop conditional from the stack and repeat the loop if truthy.
"Party is over."          # Should never happen.

Why is the party over?

~ not only discards he string; it evaluates it. Notably, it executes 0:1. Since 1 is a valid identifier (which happens to have the default value 1), this saves the value 0 in the variable 1. Therefore, the loop's conditional will be falsy, so it is executed only once.

share|improve this answer

C

Classic integer overflow.

#include<stdlib.h>

int main() {
    unsigned a = 0;
    unsigned b = 1000;
    while (a<b) {
        a++;
        b++;
    }
    puts("Hi");
    return 0;
}
share|improve this answer
1  
This may fail for signed integers, as signed integers overflow is undefined behavior. –  Dennis Jul 21 at 18:20
    
@Dennis Thanks for the advice! I'm not too good at C. –  bitpwner Jul 21 at 18:53

C/C++

The following program outputs

I'm stuck at 41...
I'm stuck at 18467...
I'm stuck at 6334...
I'm stuck at 26500...
I'm stuck at 19169...
I'm stuck at 15724...
I'm stuck at 11478...
I escaped at 29358!

(the output on your system may be different)

#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

jmp_buf b;

int my_location()
{
    int result = rand();
    if (result % 7 == 0)
        longjmp(b, result);
    return result;
}

int main()
{
    int location = setjmp(b);

    if (location)
        return printf("I escaped at %d!\n", location);

    for (;;)
    {
        printf("I'm stuck at %d...\n", my_location());
    }
}

The "infinite" loop at the end of the main function is broken

by the longjmp function, which is called when a random number becomes divisible by 7.

This is pretty standard... For people who are old enough to remember that trick (which was once pretty much the only way to implement this behavior in C).

share|improve this answer
    
I could rearrange the code so it would "execute an instruction written just after the loop" but I think it's more fun the way it is... –  anatolyg Jul 21 at 17:36

Befunge-98

This program breaks out of its infinite loop by randomly modifying itself

"ITRH"4(v
        >222Sac*%Se3*%S5%S.pp
share|improve this answer
    
if it randomly modifies itself, isn't there a chance that it will change the modifying part, and then loop forever? –  proud haskeller Jul 21 at 21:33
    
Yes. Most of the time it will create a different infinite loop, but it will occasionally generate an @ to actually stop the program. –  waylon531 Jul 21 at 21:59
    
but won't it sometimes break the self modifying part, and then, because the code isn't ever modified again, loops forever? –  proud haskeller Jul 21 at 22:18
    
can't it also generate an ^ of v in the code causing another inescapable infinite loop? –  proud haskeller Jul 21 at 22:19
    
Yes, it usually replaces one of the put commands or inserts a go command before it places an @ into the code. –  waylon531 Jul 21 at 22:35

C

Patricide

#include <stdio.h>
#include <unistd.h>

int main(void) {
    pid_t id = fork();

    if (id != 0) {
        while(1) {
            wait(1);
            printf("Apples\n");
        }
    }
    else {
        wait(5);
        kill(getppid(), 9);
    }

    printf("Bananas\n");
}

Fork a child process and enter an endless loop: child process terminates the parent process with a KILL signal.

share|improve this answer
    
This is not valid; you must actually execute some code after the infinite loop within the same function. –  Gabe Jul 21 at 20:54

C

#include <stdio.h>
int i;
int main()
{
    ++i;
    while(i)
    {
        i*=1000;
        printf("%d",i);
    }
}
share|improve this answer
    
This is not valid; you must actually execute some code after the infinite loop within the same function. –  Gabe Jul 21 at 20:55

Java with SnakeYAML library used

Know your libraries :)

import java.util.ArrayList;
import java.util.List;
import org.yaml.snakeyaml.Yaml;
public class UnLoop
{
    final static List<Object> queue = new ArrayList<>();
    public static void main(String[] args)
    {
        //running serializer nonstatic
        new Thread(()->{
        for(;;){
            if(queue.size()!=0)
            System.out.println(new Yaml().dump(
                    queue.remove(0)));

            }}).start();

        queue.add("DERP");
        queue.add(new String[]{"1","2","3","4"});
        queue.add(new java.awt.Point(1, 1));

    }
}

Snakeyaml hates to serialize certain objects due to the way it works, java.awt.point is one of then, so it stackoverflows out

to satisfy the rule the loop is now a serializing thread and the data inerted from another thread

share|improve this answer
    
This is not valid; you must actually execute some code after the infinite loop within the same function. –  Gabe Jul 21 at 20:54
    
@Gabe changed the way the program works –  masterX244 Jul 22 at 11:59
    
What code does it execute after the infinite loop? –  Gabe Jul 22 at 12:48
    
the first c++ answer isnt using code after his loop, too, and the code that is after is feeding the loop –  masterX244 Jul 22 at 17:05

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