loading...

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 a...
pic
Editor guide
Collapse
arne_mertz profile image
Arne Mertz

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;
}
Collapse
r0f1 profile image
Florian Rohrer Author

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

Collapse
sudhan96 profile image
raja sudhan

very nice friend!!

Collapse
halt_6kere9 profile image
Halt! 6 kere 9?

This is far the best 👍

Collapse
rpalo profile image
Ryan Palo

Ruby:

loop {:D}
Collapse
r0f1 profile image
Florian Rohrer Author

This gotta be the happiest loop, I've ever seen.

Collapse
dvdmuckle profile image
David Muckle
:(){:|:&};:
10 PRINT "HELLO!"
20 GOTO 10

Always gotta have the classics.

Collapse
perryahern profile image
Perry Ahern

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

Collapse
dvdmuckle profile image
David Muckle

I can do that if you'd like... dev.to/dvdmuckle/hooking-up-a-vt42... :)

Thread Thread
perryahern profile image
Perry Ahern

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.

Collapse
jessydmd profile image
Jessy
function a(){
  a();
}

a();

Endless recursivity!

Collapse
halt_6kere9 profile image
Halt! 6 kere 9?

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

Collapse
arne_mertz profile image
Arne Mertz

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

Thread Thread
gefjon profile image
Phoebe Goldman

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

(defun loop-for-ever ()
  (loop-for-ever))
(loop-for-ever)
Collapse
jessydmd profile image
Jessy

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

while(true){}

but that's a little boring.

Thread Thread
halt_6kere9 profile image
Halt! 6 kere 9?

Definitely classic but lacks the humor :)

Collapse
kajigga profile image
Kajigga

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))
Collapse
peter profile image
Peter Kim Frank

The "never-ending song" is classic. 😂

Collapse
lucianoq profile image
Luciano Quercia
var f float32
for f = 0; int(f) < 16777217; f++ {
    fmt.Println("Hello!")
}
Collapse
miffpengi profile image
Miff

Brainfuck, I guess.

+[]
Collapse
val_baca profile image
Valentin Baca

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

Collapse
parthpower profile image
Parth Parikh

Welcome to Verilog.

module tb();
    always $display("You think I will stop? Think again!");
endmodule;
Collapse
karn profile image
Karn Saheb

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

Collapse
unused profile image
unused

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(;;);
}
Collapse
patriklarsson profile image
Patrik

Only to make people hate me...

HTML

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

Collapse
_rodrigooliv profile image
Rodrigo Martins

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")
Collapse
eminemence profile image
eminemence

Shell command :
yes

Collapse
iglosiggio profile image
Ignacio Losiggio

A classical example :P

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

Or in ES2015

(a=>a(a))(a=>a(a))
Collapse
gefjon profile image
Phoebe Goldman

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);
    }
}
Collapse
andreasjakof profile image
Andreas Jakof

C#

class Program
{
   public static IEnumerable<string> HelloWorld()
   {
      while(true) yield return Hello World;
   }
   public static void Main(string[] args)
   {
      foreach (string  s in HelloWorld())
      {
         Console.WriteLine(s);
         Thread.Sleep(1000);
      }
   }
}
Collapse
r0f1 profile image
Florian Rohrer Author

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");
}
Collapse
errietta profile image
Errietta Erry Kostala
#!/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 :)
Collapse
danielescoz profile image
Daniel Escoz

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)

Collapse
eigenvalue profile image
Lucio Rossi

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>
Collapse
superfola profile image
Alexandre Plateau

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;
}
Collapse
kuziandus profile image
Dan Suzuki

Scala

@tailrec 
final def diamond(b: Boolean): Boolean = 
   if(b) diamond(b) 
   else b
Collapse
val_baca profile image
Valentin Baca

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

Thread Thread
danielkun profile image
Collapse
programliftoff profile image
Programming Liftoff

C

int main() {
  int x = 1;
  while(x>0);
  {
    x--;
  }
}
Collapse
carstenk_dev profile image
Carsten

Haskell

go = 1:go
Collapse
craigmc08 profile image
Craig McIlwrath

Isn't this program fine? It never forces evaluation of go so the program immediately exits.

Collapse
carstenk_dev profile image
Carsten

of course I assumed you would evaluate the expression (for example in the repl)

you are technical right but it's a bit like commenting to all the others and saying "it's fine as long as you don't run it" ;)


just assume a

main = print go

there if you like

Collapse
nektro profile image
Meghan (she/her)

Javascript

setInterval(function() {}, 1);
Collapse
blazselih profile image
Blaž Šelih

Z80 assembly

loop: JR loop

compiles down to two bytes: 18 FD

Collapse
leswile profile image
Jens
for(int i = 0; i < 10; i++)
{
  i--;
}
Collapse
simpgeek profile image
Nigel Kirby

2 JS classics

let a = 1
while(a !== '1')
    console.log('sup')
let a = 0.1 * 0.2
while(a !== .02)
    console.log('sup')
Collapse
benaryorg profile image
#benaryorg

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);
}
Collapse
heyayush profile image
Ayush


for (;;cout<<"forever");

Collapse
_bigblind profile image
Frederik 👨‍💻➡️🌐 Creemers

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)
Collapse
r0f1 profile image
Collapse
cgortaris profile image
Carlos Gortaris

C

while(fork());

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

Collapse
bitsinmotion profile image
Mark Ciccarello
int main()
{
   int i = 0;
   while(i < 10) {
      println("Hello world");
      i = i++;
   }

}
Collapse
thomasxbanks profile image
Thomas Banks
while (true) {
  console.log(!true)
}
Collapse
kurtgokhan profile image
Gökhan Kurt
_=        '._.'   // Dude WTF

for       (;_;)   // Stop that pls

          _=_=_   // IDC LOL
Collapse
ramriot profile image
Gary Marriott

Erlang:

loop() ->
do:someVitalTask(),
loop().

Collapse
fbielejec profile image
Filip Bielejec

Clojure

(while true (do))

(Behold the beauty of LISP :) )

Collapse
jp1337 profile image
Jp1337
int main(){
    uint8_t i=0;
    while( ++i > i++ ? i-- : --i );
}
Collapse
michie1 profile image
michie1
while(1){}
Collapse
eugeniu_rtj profile image
Eugeniu T.

Elixir:

def infinite do
    infinite
end
Collapse
johand profile image
Johan

Ruby

loop do
  puts 'trololo'
end
Collapse
sur0g profile image
sur0g
#python
for person in dumb_people_around_me:
 print('Yay!')
Collapse
terceranexus6 profile image
Paula

This post is so dangerous oh my god

Collapse
tonnoz profile image
tonnoz

Java8

The matrix has you:

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

`T

2 bytes. Language: MATL

Collapse
indra452 profile image
indra452

while (true) {}

Collapse
3leftturns profile image
Andrew T Johnson

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

Collapse
helpermethod profile image
Oliver Weiler

bash (probably sh too)

while :; do :; done
Collapse
tavogl profile image
Gustavo

Windows Programming:
:1
start
goto 1

Collapse
crhodes2 profile image
crhodes

Oooh! This is fun!

Python:

ImCrazy4You = True

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

Collapse
lnbharath profile image
Bharath

Swift :

repeat { print("Hello") } while(true)

Collapse
kenan7 profile image
Kenan

while True:
print('something')

Collapse
daanwilmer profile image
Daan Wilmer

On linux bash:

cat /dev/urandom > /dev/null

Collapse
crhodes2 profile image
crhodes

Oooh! This is fun!

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

Collapse
brunojennrich profile image
bruno jennrich

while(true);

Collapse
fzngagan profile image
fzngagan

void main(){
main();
}

Collapse
brunojennrich profile image
Collapse
ar10642 profile image
Andrew Richardson

Z80 assembly (3 bytes)

32768: JP 32768

Collapse
crhodes2 profile image
crhodes

Infinite insult in C

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

}