Challenge: Write a program that never stops

Florian Rohrer on October 19, 2017

Write an endless loop, write some confusing gotos... The rules are simple: Write a program that never stops. Language: Any. Try to keep it short... [Read Full]
markdown guide
 
 

C++

#define ever ;;
int main() {
  for(ever);
}
int main() {
    for (unsigned i = 341; i > 0; --i) {
        printf("%u\n", i--);
    }
}
int main() {
    float f = 1.0f;
    while (f < 16777218.2f) {
        printf("%f\n", f);
        f += 1;
    }
}

assembler

main:
.L2
  jmp .L2

C

int main(void) {
    int b=0, a[] = {0,1};
    while (b != (!b)[a]) {
        printf("%i\n", b=!a[b]);
    }
}
int main(void) {
  https://dev.to
  goto https;
}
 

I really like the last one. Defining a label to a comment - nice :D

 
 
 
 
:(){:|:&};:
10 PRINT "HELLO!"
20 GOTO 10

Always gotta have the classics.

 

Ah, BASIC with manually typed line numbers and GOTO... If only the screenshot were monochromatic green or amber it would be truly classic.

 

That'd be cool to see, but it'd never replace my memories of flickering Commodore PET screens from days of yore. Cool write up though, saving that to read later.

 
 

This will crash once the stack is full but nice try. :)

 

Use a language that allows optimization of tail recursion then ¯_(ツ)_/¯

Us cool kids with our tail recursion could write in, for example, Common Lisp:

(defun loop-for-ever ()
  (loop-for-ever))
(loop-for-ever)
 

Hahaha yeah it totally did crash Chrome when I tried it. I wanted to just post

while(true){}

but that's a little boring.

 

python

while 1:1

never-ending song

from itertools import cycle
import time
list = ['This is the song that never ends',
    'It just goes on and on my friends',
    'Some people started singing it, not knowing what it was',
    'And they\'ll continue singing it forever just because...']

for line in cycle(list):
    print(line)
    time.sleep(.25)

non-stop random numbers

from random import randint
def infinite_random():
    while True:
        yield randint(1,1000000000)

for x in infinite_random():
    print(x)

lots of random user information

import requests
def get_users():
    while True:
        yield requests.get('https://randomuser.me/api/').json()['results'][0]

for user in get_users():
    print('{0[name][first]} {0[name][last]} - born {0[dob]}'.format(user))
 
 
var f float32
for f = 0; int(f) < 16777217; f++ {
    fmt.Println("Hello!")
}
 
 

Welcome to Verilog.

module tb();
    always $display("You think I will stop? Think again!");
endmodule;
 

My god, this brings back memories that I've been trying to compartmentalize. :'(

 

Javascript (empty statement evaluates to true so is effectively while(true)): for(;;);

Super-Evil Javascript DON'T RUN THIS LOL: for(;;)alert();

Python: while 1:0

Shell: yes
Funny story about yes is that in Unix it's actually just a blank file, which AT&T has the copywrite for o.0

 

for(;;); endless loop is nowadays marked as [drumroll] javascript.

Kill me please.

 

The original post was tagged with javascript and dev.to has a bias toward javascript which is why it was tagged with that.

What language would you have picked? Because most languages do not have empty statements evaluate to true, so the block would have had to be for(;1;); which is not as neat IMO

 

Was missing a uninterruptible one

#include <signal.h>
void main(void) {
  sigset_t stop;
  sigemptyset (&stop);
  sigaddset(&stop, SIGINT);
  sigaddset(&stop, SIGTSTP);
  sigprocmask(SIG_BLOCK, &stop, NULL);

  for(;;);
}
 

Only to make people hate me...

HTML

<marquee>You spin my head right round, right round...</marquee>

 

Python

valuе = 0
while valuе < 1:
    value = valuе + 1

Python

i = 0
j = 10
while not i is j:
    i += 1

print("i is j: " + str(i is j))

j = 257
while not i is j:
    i += 1

print("unreachable")
 
 

C++

#include <iostream>
int main(int argc, char* argv)
{
    std::cout << "argc is " << argc << std::endl;
    std::cout << main(argc, argv);
    return main(1, {'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\0'});
}

C++ (even though the syntax highlithing is set to python)

#include <my_awesome_events_manager_lib>
using namespace my_awesome_events_manager_lib;
int main(void)
{
    auto playing = true;
    while (playing)
    {
        // handle events /!\
        if (getEvent()->type == QUIT) playing = !playing;
    }
    return 0x0;
}
 

Scala

@tailrec 
final def diamond(b: Boolean): Boolean = 
   if(b) diamond(b) 
   else b
 

This is not a program in the strict sense and surely it will never run forever, but still it's a lot of fun

<IfModule mod_ssl.c>
<VirtualHost *:443>
   RewriteEngine on
   RewriteRule ^ https://%{SERVER_NAME}/fun%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>
</IfModule>
 

Javascript (ES6):

const zero = () => Promise.resolve(0).then(zero);
zero().then(result => console.log('this does not print a zero:', result));

Technically ends because .then run on the next tick, but it permanently blocks the JS event loop (I think).

(It might eat your RAM)

 

C

// 1
int i = 0;
while(i < 10)
{
    if(i = 5)
        printf("i is 5!");
    i++;
}
// 2
for(int i = 0; i < 10; i++);
{
    printf("hello");
}
// 3
for(int i = 1; i < 11, i++;)
{
    printf("hello");
}
 
 
#!/usr/bin/env perl

$SIG{INT} = 'IGNORE';

while ( 1 ) {
  print "stop me if you can\n";
  sleep 1;
}

# Pretty standard but I went a bit further and made it ignore CTRL-C as well, so you have to `kill -9` it :)
 

Rust:

fn main() {
    loop {
    }
}

Or, for a slightly more involved example:

use std::num::Wrapping;
use std::iter::Iterator;

struct Fibs {
    n: Wrapping<usize>,
    n_minus_one: Wrapping<usize>,
}

impl Fibs {
    fn new() -> Self {
        Fibs {
            n: Wrapping(1),
            n_minus_one: Wrapping(0),
        }
    }
}

impl Iterator for Fibs {
    type Item = Wrapping<usize>;
    fn next(&mut self) -> Option<Self::Item> {
        let n_plus_one = self.n + self.n_minus_one;
        self.n_minus_one = self.n;
        self.n = n_plus_one;
        Some(n_plus_one)
    }
}

fn main() {
    let mut fibs = Fibs::new();
    while let Some(n) = fibs.next() {
        println!("{}", n);
    }
}
 
 

A classical example :P

(λx.x x)(λx.x x)

Or in ES2015

(a=>a(a))(a=>a(a))
 
 

Z80 assembly

loop: JR loop

compiles down to two bytes: 18 FD

 
 

C

while(fork());

This ends when enough sysadmins get annoyed. We used to call it "fork bomb" at the University systems.

 
 

2 JS classics

let a = 1
while(a !== '1')
    console.log('sup')
let a = 0.1 * 0.2
while(a !== .02)
    console.log('sup')
 

Using C and TCO:


#define foo(x) _foo((x),1,0)

int _foo(int to,int cur,int acc)
{
  if((cur = 0) || (to = cur))
  {
    return acc;
  }
  return _foo(to,cur+1,acc+cur);
}

int main(void)
{
  return foo(10);
}
 

his technically doesn't run forever, but takes longer than you'd expect:

Python:

import re

exp = re.compile("a(b|c+)*d")
exp.match("a" + "c"*100)
 
 
_=        '._.'   // Dude WTF

for       (;_;)   // Stop that pls

          _=_=_   // IDC LOL
 
 
[][{toString:function(){[][this]}}]

Sure, while it does eventually end due to too much recursion (no such thing!), theoretically if it didn't...

 
 

Clojure

(while true (do))

(Behold the beauty of LISP :) )

 
#python
for person in dumb_people_around_me:
 print('Yay!')
 
int main()
{
   int i = 0;
   while(i < 10) {
      println("Hello world");
      i = i++;
   }

}
 
int main(){
    uint8_t i=0;
    while( ++i > i++ ? i-- : --i );
}
 
 
 

Java8

The matrix has you:

Stream.iterate("", i -> i = Character
    .toString((char) new Random().nextInt(255)))
.forEach(i-> System.out.print(i));
 
Stream.iterate('a', i-> i= (char)new Random().nextInt(255)).forEach(i-> System.out.print(i));
 
 
 
 
 
 

Oooh! This is fun!

Python:

ImCrazy4You = True

while (ImCrazy4You):
print "I will always stalk you, forever!";

 
 
 
 
 
 

The Earth was designed to run forever, until the Vogons needed to put in a hyperspace expressway. 😂

 
 

Infinite insult in C

int YourIQ = 0;
while (YourIQ < 1)
{
    printf("You're stupid! ");

}
 
 
 

Oooh! This is fun!

Python:
ImCrazy4You = True
while (ImCrazy4You):
print "I will always be watching you, forever!";

 
 
code of conduct - report abuse