# Break out of a loop [duplicate]

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


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

loop()
print("I escaped!")


## marked as duplicate by Martin Ender, Kyle Kanos, William Barbosa, Peter Taylor, Digital TraumaJul 21 '14 at 21:01

• I think this should be tagged with underhanded – William Barbosa Jul 21 '14 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 '14 at 18:02
• @DatEpicCoderGuyWhoPrograms it is a popularity contents. My guess break wouldn't be very popular. – Danny Jul 21 '14 at 19:46
• 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 '14 at 20:03
• 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 '14 at 21:39

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

# C

Classic integer overflow.

#include<stdlib.h>

int main() {
unsigned a = 0;
unsigned b = 1000;
while (a<b) {
a++;
b++;
}
puts("Hi");
return 0;
}

• This may fail for signed integers, as signed integers overflow is undefined behavior. – Dennis Jul 21 '14 at 18:20
• @Dennis Thanks for the advice! I'm not too good at C. – Vectorized Jul 21 '14 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).

• 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 '14 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

• 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 '14 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 '14 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 '14 at 22:18
• can't it also generate an ^ of v in the code causing another inescapable infinite loop? – proud haskeller Jul 21 '14 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 '14 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.

• This is not valid; you must actually execute some code after the infinite loop within the same function. – Gabe Jul 21 '14 at 20:54

## C

#include <stdio.h>
int i;
int main()
{
++i;
while(i)
{
i*=1000;
printf("%d",i);
}
}

• This is not valid; you must actually execute some code after the infinite loop within the same function. – Gabe Jul 21 '14 at 20:55

# Java with SnakeYAML library used

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
for(;;){
if(queue.size()!=0)
System.out.println(new Yaml().dump(
queue.remove(0)));

}}).start();