DEV Community

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...
Collapse
 
rpalo profile image
Ryan Palo

Ruby:

loop {:D}
Collapse
 
r0f1 profile image
Florian Rohrer

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

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

Always gotta have the classics.

Collapse
 
perryahern profile image
Perry Ahern • Edited

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
 
lucianoq profile image
Luciano Quercia
var f float32
for f = 0; int(f) < 16777217; f++ {
    fmt.Println("Hello!")
}
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
 
miffpengi profile image
Miff

Brainfuck, I guess.

+[]
Collapse
 
arne_mertz profile image
Arne Mertz • Edited

C++

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

assembler

main:
.L2
  jmp .L2
Enter fullscreen mode Exit fullscreen mode

C

int main(void) {
    int b=0, a[] = {0,1};
    while (b != (!b)[a]) {
        printf("%i\n", b=!a[b]);
    }
}
Enter fullscreen mode Exit fullscreen mode
int main(void) {
  https://dev.to
  goto https;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
r0f1 profile image
Florian Rohrer

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

Collapse
 
halt_6kere9 profile image
Halt! 6 kere 9?

This is far the best 👍

Collapse
 
sudhan96 profile image
raja sudhan

very nice friend!!

Collapse
 
val_baca profile image
Valentin Baca • Edited

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 • Edited

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 • Edited

Shell command :
yes

Collapse
 
danielescoz profile image
Daniel Escoz • Edited

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
 
r0f1 profile image
Florian Rohrer • Edited

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

Scala

@tailrec 
final def diamond(b: Boolean): Boolean = 
   if(b) diamond(b) 
   else b
Collapse
 
errietta profile image
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
 
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 • Edited

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
 
lexplt profile image
Alexandre Plt • Edited

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
 
programliftoff profile image
Programming Liftoff

C

int main() {
  int x = 1;
  while(x>0);
  {
    x--;
  }
}
Collapse
 
nektro profile image
Meghan (she/her)

Javascript

setInterval(function() {}, 1);
Collapse
 
val_baca profile image
Valentin Baca • Edited

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
Daniel Albuschat

C

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
 
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
 
iglosiggio profile image
Ignacio Losiggio • Edited

A classical example :P

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

Or in ES2015

(a=>a(a))(a=>a(a))
Collapse
 
heyay profile image
Ayush • Edited


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

Collapse
 
benaryorg profile image
#benaryorg • Edited

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
 
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
 
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
 
blazselih profile image
Blaž Šelih

Z80 assembly

loop: JR loop

compiles down to two bytes: 18 FD

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
Florian Rohrer
Collapse
 
leswile profile image
Jens • Edited
for(int i = 0; i < 10; i++)
{
  i--;
}
Collapse
 
jp1337 profile image
Jp1337
int main(){
    uint8_t i=0;
    while( ++i > i++ ? i-- : --i );
}
Collapse
 
eugeniu_rtj profile image
Eugeniu T. • Edited

Elixir:

def infinite do
    infinite
end
Collapse
 
ramriot profile image
Gary Marriott • Edited

Erlang:

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

Collapse
 
kurtgokhan profile image
Gökhan Kurt
_=        '._.'   // Dude WTF

for       (;_;)   // Stop that pls

          _=_=_   // IDC LOL
Collapse
 
fbielejec profile image
Filip Bielejec

Clojure

(while true (do))

(Behold the beauty of LISP :) )

Collapse
 
hryggrbyr profile image
Thomas Rigby
while (true) {
  console.log(!true)
}
Collapse
 
nullpo profile image
Pablo

`T

2 bytes. Language: MATL

Collapse
 
terceranexus6 profile image
Paula

This post is so dangerous oh my god

Collapse
 
tonnoz profile image
tonnoz • Edited

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
 
johand profile image
Johan

Ruby

loop do
  puts 'trololo'
end
Collapse
 
michie1 profile image
michie1
while(1){}
Collapse
 
sur0g profile image
sur0g • Edited
#python
for person in dumb_people_around_me:
 print('Yay!')
Collapse
 
bitsinmotion profile image
Mark Ciccarello
int main()
{
   int i = 0;
   while(i < 10) {
      println("Hello world");
      i = i++;
   }

}
Collapse
 
lnbharath profile image
Bharath • Edited

Swift :

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

Collapse
 
kenan7 profile image
Kenan

while True:
print('something')

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
 
indra452 profile image
indra452

while (true) {}

Collapse
 
crhodes2 profile image
crhodes

Oooh! This is fun!

Python:

ImCrazy4You = True

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

Collapse
 
daanwilmer profile image
Daan Wilmer

On linux bash:

cat /dev/urandom > /dev/null

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
 
brunojennrich profile image
bruno jennrich

for(;;);

Collapse
 
crhodes2 profile image
crhodes

Infinite insult in C

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

}
Collapse
 
brunojennrich profile image
bruno jennrich

while(true);

Collapse
 
crhodes2 profile image
crhodes • Edited

Oooh! This is fun!

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

Collapse
 
fzngagan profile image
fzngagan

void main(){
main();
}