Break out of a loop

2

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

Ypnypn

Posted 2014-07-21T16:36:54.187

Reputation: 10 485

Question was closed 2014-07-21T21:01:40.263

2I think this should be tagged with underhanded – William Barbosa – 2014-07-21T16:46:23.570

Are we allowed to use something such as break in python? You didn't seem to exactly specify that. – DatEpicCoderGuyWhoPrograms – 2014-07-21T18:02:37.340

@DatEpicCoderGuyWhoPrograms it is a popularity contents. My guess break wouldn't be very popular. – Danny – 2014-07-21T19:46:46.177

1I 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 – 2014-07-21T20:03:44.037

1why 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 – 2014-07-21T21:39:49.640

@Greg clarified. – Ypnypn – 2014-07-21T22:11:17.287

@proudhaskeller My comment explaining why I decided to close-vote as (indirect) duplicate was automatically removed when the 5th vote came in. My argument is that most of the answers to the other question probably fail at some boolean check when trying to get out of a loop. All you need to do is invert that boolean and you have a valid submission. – Martin Ender – 2014-07-21T22:12:02.433

@MartinBüttner You can assert that but, there are other very creative ways of doing what this question asks as shown by the answers below. This is not a duplicate. – gxtaillon – 2014-07-22T00:42:25.530

@gxtaillon well out of the current answers, the only valid and interesting ones could be trivially adapted to be valid answers to the other question. The guidelines for "is it a duplicate" are not "Is it a different question?", but "Can answers be copied over without significant change?" which is definitely the case for many answers. – Martin Ender – 2014-07-22T07:08:39.080

Answers

8

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.

Dennis

Posted 2014-07-21T16:36:54.187

Reputation: 196 637

4

C

Classic integer overflow.

#include<stdlib.h>

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

Vectorized

Posted 2014-07-21T16:36:54.187

Reputation: 3 486

1This may fail for signed integers, as signed integers overflow is undefined behavior. – Dennis – 2014-07-21T18:20:03.517

@Dennis Thanks for the advice! I'm not too good at C. – Vectorized – 2014-07-21T18:53:27.583

1

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

anatolyg

Posted 2014-07-21T16:36:54.187

Reputation: 10 719

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 – 2014-07-21T17:36:12.740

1

Befunge-98

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

"ITRH"4(v
        >222Sac*%Se3*%S5%S.pp

waylon531

Posted 2014-07-21T16:36:54.187

Reputation: 411

if it randomly modifies itself, isn't there a chance that it will change the modifying part, and then loop forever? – proud haskeller – 2014-07-21T21:33:31.233

Yes. Most of the time it will create a different infinite loop, but it will occasionally generate an @ to actually stop the program. – waylon531 – 2014-07-21T21:59:04.477

but won't it sometimes break the self modifying part, and then, because the code isn't ever modified again, loops forever? – proud haskeller – 2014-07-21T22:18:56.807

can't it also generate an ^ of v in the code causing another inescapable infinite loop? – proud haskeller – 2014-07-21T22:19:58.760

Yes, it usually replaces one of the put commands or inserts a go command before it places an @ into the code. – waylon531 – 2014-07-21T22:35:20.563

1

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.

Graph Theory

Posted 2014-07-21T16:36:54.187

Reputation: 181

This is not valid; you must actually execute some code after the infinite loop within the same function. – Gabe – 2014-07-21T20:54:20.223

0

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

masterX244

Posted 2014-07-21T16:36:54.187

Reputation: 3 942

This is not valid; you must actually execute some code after the infinite loop within the same function. – Gabe – 2014-07-21T20:54:43.210

@Gabe changed the way the program works – masterX244 – 2014-07-22T11:59:52.133

What code does it execute after the infinite loop? – Gabe – 2014-07-22T12:48:30.623

the first c++ answer isnt using code after his loop, too, and the code that is after is feeding the loop – masterX244 – 2014-07-22T17:05:36.970

0

C

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

bacchusbeale

Posted 2014-07-21T16:36:54.187

Reputation: 1 235

This is not valid; you must actually execute some code after the infinite loop within the same function. – Gabe – 2014-07-21T20:55:25.560