2
\$\begingroup\$

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!")
\$\endgroup\$
9
  • 2
    \$\begingroup\$ I think this should be tagged with underhanded \$\endgroup\$ Jul 21, 2014 at 16:46
  • \$\begingroup\$ Are we allowed to use something such as break in python? You didn't seem to exactly specify that. \$\endgroup\$ Jul 21, 2014 at 18:02
  • \$\begingroup\$ @DatEpicCoderGuyWhoPrograms it is a popularity contents. My guess break wouldn't be very popular. \$\endgroup\$
    – Danny
    Jul 21, 2014 at 19:46
  • 1
    \$\begingroup\$ 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? \$\endgroup\$ Jul 21, 2014 at 20:03
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Jul 21, 2014 at 21:39

7 Answers 7

8
\$\begingroup\$

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.

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

C

Classic integer overflow.

#include<stdlib.h>

int main() {
    unsigned a = 0;
    unsigned b = 1000;
    while (a<b) {
        a++;
        b++;
    }
    puts("Hi");
    return 0;
}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ This may fail for signed integers, as signed integers overflow is undefined behavior. \$\endgroup\$
    – Dennis
    Jul 21, 2014 at 18:20
  • \$\begingroup\$ @Dennis Thanks for the advice! I'm not too good at C. \$\endgroup\$
    – Vectorized
    Jul 21, 2014 at 18:53
1
\$\begingroup\$

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

\$\endgroup\$
1
  • \$\begingroup\$ 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... \$\endgroup\$
    – anatolyg
    Jul 21, 2014 at 17:36
1
\$\begingroup\$

Befunge-98

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

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

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.

\$\endgroup\$
1
  • \$\begingroup\$ This is not valid; you must actually execute some code after the infinite loop within the same function. \$\endgroup\$
    – Gabe
    Jul 21, 2014 at 20:54
0
\$\begingroup\$

C

#include <stdio.h>
int i;
int main()
{
    ++i;
    while(i)
    {
        i*=1000;
        printf("%d",i);
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ This is not valid; you must actually execute some code after the infinite loop within the same function. \$\endgroup\$
    – Gabe
    Jul 21, 2014 at 20:55
0
\$\begingroup\$

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

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

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