140
\$\begingroup\$

Your task is to create the shortest infinite loop!

The point of this challenge is to create an infinite loop producing no output, unlike its possible duplicate. The reason to this is because the code might be shorter if no output is given.

Rules

  • Each submission must be a full program.
  • You must create the shortest infinite loop.
  • Even if your program runs out of memory eventually, it is still accepted as long as it is running the whole time from the start to when it runs out of memory. Also when it runs out of memory, it should still not print anything to STDERR.
  • The program must take no input (however, reading from a file is allowed), and should not print anything to STDOUT. Output to a file is also forbidden.
  • The program must not write anything to STDERR.
  • Feel free to use a language (or language version) even if it's newer than this challenge. -Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. :D
  • Submissions are scored in bytes, in an appropriate (pre-existing) encoding, usually (but not necessarily) UTF-8. Some languages, like Folders, are a bit tricky to score - if in doubt, please ask on Meta.
  • This is not about finding the language with the shortest infinite loop program. This is about finding the shortest infinite loop program in every language. Therefore, I will not accept an answer.
  • If your language of choice is a trivial variant of another (potentially more popular) language which already has an answer (think BASIC or SQL dialects, Unix shells or trivial Brainf**k-derivatives like Alphuck), consider adding a note to the existing answer that the same or a very similar solution is also the shortest in the other language.
  • There should be a website such as Wikipedia, Esolangs, or GitHub for the language. For example, if the language is CJam, then one could link to the site in the header like #[CJam](http://sourceforge.net/p/cjam/wiki/Home/), X bytes.
  • Standard loopholes are not allowed.

(I have taken some of these rules from Martin Büttner's "Hello World" challenge)


Please feel free to post in the comments to tell me how this challenge could be improved.

Catalogue

This is a Stack Snippet which generates both an alphabetical catalogue of the used languages, and an overall leaderboard. To make sure your answer shows up, please start it with this Markdown header:

# Language name, X bytes

Obviously replacing Language name and X bytes with the proper items. If you want to link to the languages' website, use this template, as posted above:

#[Language name](http://link.to/the/language), X bytes

Now, finally, here's the snippet: (Try pressing "Full page" for a better view.)

var QUESTION_ID=59347;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=41805;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"//api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"//api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='<h1>'+c.body.replace(OVERRIDE_REG,'')+'</h1>'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery('<a>'+lang+'</a>').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang,user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase())return 1;if(a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase())return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}
body{text-align:left!important}#answer-list{padding:10px;width:500px;float:left}#language-list{padding:10px;padding-right:40px;width:500px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table>

\$\endgroup\$
13
  • 50
    \$\begingroup\$ I've got to start posting programs with a negative byte count to beat all these empty files! \$\endgroup\$
    – CJ Dennis
    Oct 3, 2015 at 4:32
  • 4
    \$\begingroup\$ This challenge is interesting because it brings out lots of 0 byte languages (some of which are NOT esolangs). FWIW, most declarative languages have an implicit infinite loop because declarative languages don't have loops in their syntax (they assume they're running in an infinite loop). Ladder diagrams are perhaps among the oldest such languages. Then you have the Instruction Language (IL), a sort of assembly for PLCs that also assume an infinite loop. ILs, like assembly are different between manufacturers \$\endgroup\$
    – slebetman
    Oct 5, 2015 at 9:36
  • \$\begingroup\$ Are programs that read and execute their own source code allowed, or does file I/O break the "must take no input" rule? \$\endgroup\$ Oct 6, 2015 at 13:05
  • 1
    \$\begingroup\$ @ThisSuitIsBlackNot Yes, file input is allowed. \$\endgroup\$
    – user41805
    Oct 6, 2015 at 16:47
  • \$\begingroup\$ Can you print "", an empty string? \$\endgroup\$
    – AAM111
    Mar 7, 2016 at 23:39

553 Answers 553

1
3 4
5
6 7
19
3
\$\begingroup\$

evil, 2 bytes

mb

Nothing to see here, just another self-GOTO...

\$\endgroup\$
3
\$\begingroup\$

MATL, 3 2 bytes

Quite simple really:

`T

`    # Do ... while
 T   # True
     # Implicit end, normally: ]

Try it online here (Please stop it after testing, don't keep it running).

\$\endgroup\$
3
\$\begingroup\$

GPRX 3000, 1 byte

g

Sets the IP to the value of register A (which is initially 0).

\$\endgroup\$
3
\$\begingroup\$

Seed, 3 bytes

0 0

Equivalent to an empty Befunge program.

\$\endgroup\$
3
\$\begingroup\$

Noobinary, 4 bytes

0000

0000 is a single instruction that jumps to the last 00 (or start of program) if the top of stack is 0.

\$\endgroup\$
3
\$\begingroup\$

Barely, 0 bytes


That's right! If the Barely interpreter receives the empty program, then it just hangs. Normally, the code would be terminated with a ~ to separate it from input, so the interpreter keeps reading EOF and never runs anything. Tested on DOSBox v0.74 using input redirection.

\$\endgroup\$
3
\$\begingroup\$

Subskin, 6 bytes








A series of six newlines. It contains two instructions, both of which set the IP to the second instruction.

\$\endgroup\$
3
\$\begingroup\$

BASIC, 8 bytes

1 GOTO 1

Goto self

\$\endgroup\$
3
\$\begingroup\$

Brachylog, 2 bytes

=\

Takes no input and no output.

Explanation

= will label the input with an integer. \ is always false and will therefore trigger backtracking. Since the input has no constraints, it will unify as following, through backtracking: 0, then 1, then -1, then 2, etc. This will go on forever.

\$\endgroup\$
0
3
\$\begingroup\$

Sesos, 2 bytes

0000000: 080a                                              ..

Try it online! Check Debug to see the generated binary code.

How it works

The binary file above has been generated by assembling the following SASM code.

nop       ; Set an entry marker.
    add 1 ; Increment the current cell.
          ; (implicit jnz)
          ;     If the integer in the current cell is non-zero,
          ;     jump to the previous instruction.
\$\endgroup\$
3
\$\begingroup\$

Gaot++, 27 bytes

bleeeet bleeeeeet bleeeeeet

bleeeet enters the loop, and bleeeeeet bleeeeeet switches IP direction repeatedly.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ fun fact: if you're a goat and you say this program you will rotate in a circle forever \$\endgroup\$
    – Downgoat
    Jul 26, 2016 at 20:00
3
\$\begingroup\$

Element, 3 bytes

!{}

The control stack is initially empty, the ! negates it to truthy, and {} is a loop-while-true which never ends.

\$\endgroup\$
3
\$\begingroup\$

DC, 6 bytes

[dx]dx

...puts the constant string [dx] on the stack, duplicate it (d command), pop and interprete string (x command)...

\$\endgroup\$
3
\$\begingroup\$

Bash or perl, 6 bytes

exec$0

I realize that are both bash solutions and perl solutions this length or shorter, but there are no dual-language solutions. Yup, it runs with either language.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Bash answers are always nice to see! Welcome to PPCG. \$\endgroup\$
    – Steven H.
    Sep 28, 2016 at 0:40
  • \$\begingroup\$ Put an empty line above it, and it will be a solution for bash, perl and Befunge-93 (and possible several other languages as well) \$\endgroup\$
    – Abigail
    Jun 9, 2020 at 21:42
3
\$\begingroup\$

Casio FX-7000G, 5 bytes

Lbl 0
Goto 0

Quite self-explanatory: Goto 0 indefinitely jumps back to the beginning of the program. The calculator stores each token as a byte, so Lbl and Goto are 1 byte each.

\$\endgroup\$
3
\$\begingroup\$

tinylisp, 13 bytes

((v(d f(q(L(f

Parenthesis autocompletion really helps!

We define a function f that calls itself using tail-call recursion. Functions in tinylisp are lists containing two elements: parameter list and expression. Here, our parameter list is L (which makes this a variadic function: L is bound to a list of all arguments) and our expression is (f) (calling the function with no arguments).

((v(d f(q(L(f))))))
         (L(f))      The function list
       (q      )     Quoted to prevent evaluation
   (d f         )    Define f to be that list
 (v              )   The d call returns the name f; evaluate it to get the function itself
(                 )  Call the function

Use Ctrl-C to halt execution.

\$\endgroup\$
3
\$\begingroup\$

APL, 2 bytes

→1 go to line 1 (this line)

\$\endgroup\$
3
\$\begingroup\$

Batch, 9 bytes.

a:
goto a

 

\$\endgroup\$
3
\$\begingroup\$

Beatnik, 8 bytes

K A XX K

Push a number, 1 in this case. Pop a number, if not zero skip back 4(crossed out 4) 5. There seems to be an issue with the interpreter so we need to skip back 5 instructions rather than 4.

Of course the example on the esolangs page is better.

Ha, an interminable line!

or my version

Start a neverending tale?
\$\endgroup\$
3
  • \$\begingroup\$ It seems like you've been caught by an off-by-one error. Replace the Y with a K to fix. Also, you've got a leading space (not included in the bytecount nor necessary). You can also add a Try It Online link. \$\endgroup\$
    – NieDzejkob
    Mar 6, 2018 at 14:14
  • \$\begingroup\$ @NieDzejkob I have changed this, but I think the interpreter is bugged in this respect. Going back 5 instructions when there is only 4 instructions seems a bit wrong. I don't think an infinite loop on TIO is a good idea. \$\endgroup\$
    – MickyT
    Mar 6, 2018 at 18:21
  • \$\begingroup\$ @MickyT TIO will self terminate code if it runs over 1 minute. \$\endgroup\$ Apr 15, 2018 at 1:52
3
\$\begingroup\$

C (tcc), x86_64, 10 bytes

main=-277;

Try it online!

How it works

This writes the int -277 (ebfeffff in little endian) to the memory location of main.

eb is JMP and is to be followed by a signed 8-bit address indicating where to jump to. fe is -2, so we jump back to eb and start over.

\$\endgroup\$
3
\$\begingroup\$

TI-BASIC, 4 Bytes

While 1
End

Also:

Lbl A
Goto A



This last language isn't really an answer, as the language does not exist… yet. So, yeah, just some information, and how one might accomplish this task

Simplex, 1 Byte

O

Simple enough. Simplex has the O command, which goes to the _N_th character in the source code, with N being the current byte. Since, by default, a byte is 0, this continues to go to the first character in the source code (zero-based).

\$\endgroup\$
4
  • 1
    \$\begingroup\$ TI-BASIC is 4 bytes. The 10-byte program header is counted in the MEM menu, but not here. \$\endgroup\$
    – lirtosiast
    Oct 2, 2015 at 19:39
  • \$\begingroup\$ Oh! Thanks. ^_^ \$\endgroup\$ Oct 2, 2015 at 20:35
  • \$\begingroup\$ Why not simply, for a program named W, :pgrmW? \$\endgroup\$
    – DDPWNAGE
    Feb 17, 2016 at 7:38
  • \$\begingroup\$ @DDPWNAGE because then (1) I would have to include the ten byte header, and/or (2) because the calculator will run out of resources. \$\endgroup\$ Feb 17, 2016 at 12:47
3
\$\begingroup\$

Z80Golf, 1 byte

00000000: c3                                       .

Try it online!

A jump opcode. Since memory is padded with zeroes, the argument is $0000, so that the PC forever jumps from $0000 to $0000.

\$\endgroup\$
3
\$\begingroup\$

µ6, 1 byte

@+

Try it online!

Explanation

The µ-operator takes a function and returns the least \$n\$ that results in a \$0\$ and since there is no \$n\$ such that \$n+1 = 0\$ this program won't terminate:

@   -- µ-operator applied to
 +  -- | successor function
\$\endgroup\$
3
\$\begingroup\$

Lua, 9 bytes

Here are all of the different ways (that I know of) to make an infinite loop in Lua, from shortest to longest:

Goto loop (Lua 5.2.0 beta-rc1 only) at 9 bytes:

@a:goto a

This is no longer possible in the latest version of Lua since the syntax for goto has changed, so this is now the shortest infinite loop at 11 bytes:

::a::goto a

The best that you can do using a while loop is 13 bytes by using an empty string, which Lua considers to be truthy, as the conditional:

while""do end

Here is a 14 byte repeat until loop using an uninitialized variable, which is always nil, as the conditional:

repeat until a

Tied with the return until loop, as well as my personal favorite, a recursive function using load() at 16 14 bytes: (-2 bytes thanks to Jonathan French)

f=load"f()"f()

An infinite for loop made by Jo King at 18 bytes:

for _=1,1,0 do end

Finally, the longest of the methods that I know of, a normal recursive function at 22 bytes:

function f()f()end f()

I'm curious to see if anyone can find some other methods.

\$\endgroup\$
5
  • \$\begingroup\$ I think for _=1,1,1e-16 do end (22 bytes) could work as an infinite for loop. \$\endgroup\$ Aug 6, 2018 at 2:01
  • 2
    \$\begingroup\$ Could the outer parentheses in f=load("f()")f() not be omitted? \$\endgroup\$ Aug 6, 2018 at 2:11
  • 1
    \$\begingroup\$ Thanks for the suggestion with the load loop, that would work. However wouldn't the for loop that you suggested eventually end, given enough time? \$\endgroup\$
    – GalladeGuy
    Aug 7, 2018 at 2:09
  • \$\begingroup\$ Well now I feel dumb for not thinking of that myself. Added. \$\endgroup\$
    – GalladeGuy
    Aug 7, 2018 at 2:24
  • \$\begingroup\$ I based my loop on the fact that 1+1e-16 == 1; I guess using an actual zero works too ... \$\endgroup\$ Aug 7, 2018 at 12:38
3
\$\begingroup\$

Shakespeare Programming Language, 61 bytes

,.Ajax,.Act I:.Scene I:.[Exeunt][Enter Ajax]Ajax:Let usAct I.

Try it online!

It's totally legal to only ever use one character in a play; just don't make him do anything other than loop the program forever, exiting and entering the stage constantly.

\$\endgroup\$
3
\$\begingroup\$

Stack Cats -m, 5 4 bytes

{>}I

Try it online!

-1 byte thanks to negative seven

        Since there is no input, the stack starts with nothing but -1 on the top.
{       Remember the current value on top of the stack, and loop:
 >      Move the head right on the tape of stacks. (All of them are filled with zeroes.)
  }     Repeat while the top of the stack is not as it was remembered.
   I    Since the loop goes on forever, this is just to make the program legal.
\$\endgroup\$
3
  • \$\begingroup\$ Since the choice of central involution doesn't matter, the shortest corresponding program without a flag to mirror is -(>)(<)-, which is not a cat program on account of failing to terminate. \$\endgroup\$ May 31, 2019 at 6:56
  • 1
    \$\begingroup\$ You can save a byte by using a {} loop, removing the need for -. \$\endgroup\$ May 31, 2019 at 8:50
  • \$\begingroup\$ Ah, thanks! I was sure that was the right loop until I actually figured out what I was doing, and then I promptly forgot. \$\endgroup\$ May 31, 2019 at 8:54
3
\$\begingroup\$

Brainetry, 41 bytes

The 41-byter is a golf of this Brainetry program with 133 bytes:

This program is useless.
This program is useless because it runs forever.
This program is useless because it does absolutely nothing.

and the golfed version:

a b c d
a b c d e f g h
a b c d e f g h i
\$\endgroup\$
3
\$\begingroup\$

Flurry -nnn, 10 bytes

(<>{}{}){}

Try it online!

Don't be afraid to click Run; it will stop immediately, complaining the program didn't finish in 10000 steps. Change the step limit and you can see that it is reducing into the same expression over and over. Running in the original Haskell interpreter actually runs an infinite loop.

While Flurry looks like Brain-Flak, it lacks explicit looping support. Instead, because it is functional and primarily designed with combinators, we can implement the Omega combinator S I I (S I I), which endlessly reduces to itself.

The nilad <> evaluates to S and {} pops an item from the stack. When the stack is empty, I is popped. The monad (f g h...) evaluates f g h... as function application, and pushes the result to the stack.

(<>{}{}){}  Full program
 <>         S
   {}       I
     {}     I
(      )    Evaluate to (S I I) and push it to stack
        {}  Pop (S I I)
            The entire program evaluates to (S I I)(S I I) = Omega
\$\endgroup\$
3
\$\begingroup\$

Vyxal, 1 byte

{

Try it Online!

-3 thanks to answering the right question

Explained

{      # Start an infinite while loop
\$\endgroup\$
0
3
\$\begingroup\$

C (GNU-EFI), 0 bytes

Yes, a C GNU-EFI program won't exit. You need to return for it to exit. Will not say anything, just hang.
And yes, it works with a standart GNU-EFI Makefile.
I used this one:

ARCH            = $(shell uname -m | sed s,i[3456789]86,ia32,)

OBJS            = main.o
TARGET          = main.efi

EFIINC          = /usr/include/efi
EFIINCS         = -I$(EFIINC) -I$(EFIINC)/$(ARCH) -I$(EFIINC)/protocol
LIB             = /usr/lib
EFILIB          = /usr/lib/
EFI_CRT_OBJS    = $(EFILIB)/crt0-efi-$(ARCH).o
EFI_LDS         = $(EFILIB)/elf_$(ARCH)_efi.lds

CFLAGS          = $(EFIINCS) -fno-stack-protector -fpic \
          -fshort-wchar -mno-red-zone -Wall
ifeq ($(ARCH),x86_64)
  CFLAGS += -DEFI_FUNCTION_WRAPPER
endif

LDFLAGS         = -nostdlib -znocombreloc -T $(EFI_LDS) -shared \
          -Bsymbolic -L $(EFILIB) -L $(LIB) $(EFI_CRT_OBJS)

all: $(TARGET)

main.so: $(OBJS)
    ld $(LDFLAGS) $(OBJS) -o $@ -lefi -lgnuefi

%.efi: %.so
    objcopy -j .text -j .sdata -j .data -j .dynamic \
        -j .dynsym  -j .rel -j .rela -j .reloc \
        --target=efi-app-$(ARCH) $^ $@

Hope this counts. And yes I tested this on a virtual machine.

\$\endgroup\$
2
  • \$\begingroup\$ Welcome to Code Golf! This is interesting, although I'm not sure if it counts as a loop. \$\endgroup\$ Feb 18, 2021 at 17:33
  • \$\begingroup\$ But does it loop? \$\endgroup\$
    – Mark
    Apr 24, 2021 at 23:30
1
3 4
5
6 7
19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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