145
\$\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\$
14
  • 52
    \$\begingroup\$ I've got to start posting programs with a negative byte count to beat all these empty files! \$\endgroup\$
    – CJ Dennis
    Commented 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
    Commented 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\$ Commented Oct 6, 2015 at 13:05
  • 1
    \$\begingroup\$ @ThisSuitIsBlackNot Yes, file input is allowed. \$\endgroup\$
    – user41805
    Commented Oct 6, 2015 at 16:47
  • \$\begingroup\$ Can you print "", an empty string? \$\endgroup\$
    – AAM111
    Commented Mar 7, 2016 at 23:39

581 Answers 581

1 2
3
4 5
20
6
\$\begingroup\$

Binary Lambda Calculus, 3 bytes

Before I dive into the explanation, let's start with the program itself.

F†€

Trust me, it's pure luck that they're all printable, and I'll get to why it is 2 1/4 bytes instead of 3 after the explanation. I'll explain this by walking through the process I took to create this program.

To start, BLC programs are just lambda calculus programs encoded in a special way. With this in mind, let's begin with the lambda calculus program that enters an infinite loop, known as omega.

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

This results in an infinite loop because, according to Wikipedia, it reduces to itself after a single beta-reduction. To convert this into BLC, we must first convert it to De Bruijn indices. It converts into the following:

.λ.11λ.11 (The dots after the λs are necessary for BLC but not part of De Bruijn indices)

Okay, now that it's in De Bruijin indices we can now convert it into BLC where λ translates to 00, function application or . translates to 01, and numbers are represented as 1^n0 where n is the number. Knowing this, it translates into the following binary:

01 00 01 10 10 00 01 10 10

This is why it's 2 1/4 bytes. As BLC instructions aren't full bytes (with the exception of 7), it is rare for programs to fit exactly into a certain byte count. To turn this into hex, we have to pad it in order to make it fit into 3 bytes. Doing this yields the following:

46 86 80

There we have the hex dump of our program! It runs in an infinite loop, doesn't run out of memory to my knowledge, doesn't output anything, and is a complete program that can be saved and run by piping the contents of the file to the official interpreter. You can also pipe the binary text to the interpreter and add the -b flag, to demonstrate that the non-padded version can be run.

\$\endgroup\$
6
\$\begingroup\$

Cubix, 0 bytes


Alternatively, any single character does exactly the same.

Test it online!

Cubix is a stack-based 2D language, created by me in March 2016. Cubix differs from ordinary 2D languages in that it's not strictly 2D: the code is wrapped around a cube. Any one-byte program wraps to this cube net:

   ?
>. . . .
   .

where ? represents the character, and the IP (instruction pointer) starts at the arrow. . is simply a no-op, and when the IP reaches the right side of the cube net, it simply wraps back around to the left. Thus, any 1-byte program does nothing forever, no matter what the character is (as long as it's not whitespace).

Thanks to @ErikGolferエリックゴルファー for reminding me that the empty program does the same. When Cubix was originally created, this didn't work, because the interpreter created a cube of size 0 and threw an error when it tried to run. This was fixed a while ago, and it is now impossible to cause an error in Cubix.

\$\endgroup\$
0
6
\$\begingroup\$

Java6 : 25 Bytes

In Java 6 and previous versions you can execute static initialization block without having main in your class file.

class A{static{for(;;);}}
\$\endgroup\$
4
  • 3
    \$\begingroup\$ Wouldn't for(;;); work just as well as for(int i=1;i>0;);, or is there some restriction in Java 6? \$\endgroup\$ Commented Oct 4, 2015 at 0:00
  • 2
    \$\begingroup\$ while(true) is shorter than and as valid as for(int i=1;i>0;). \$\endgroup\$ Commented May 29, 2016 at 15:47
  • 1
    \$\begingroup\$ Why is System.exit(0); needed? \$\endgroup\$
    – Oskar Skog
    Commented Aug 14, 2021 at 9:07
  • \$\begingroup\$ @OskarSkog It's not needed, just added to terminate the loop. Let me correct. \$\endgroup\$ Commented Aug 14, 2021 at 11:06
5
\$\begingroup\$

Processing, 8 bytes

for(;;);


This is based on Geobit's answer in Java


Although the code below is not the shortest, it is one of Processing's specialties.

void draw(){}

This draw statement repeats itself over and over again. It is one of the differences between Processing and Java.

\$\endgroup\$
1
  • 5
    \$\begingroup\$ You can also add JavaScript to your title, code stays the same=) \$\endgroup\$
    – flawr
    Commented Oct 2, 2015 at 18:11
5
\$\begingroup\$

CJam, 4 bytes

1{}h

Put a 1 on the stack, and loop until 1 is no longer truthy. Using h means that the number is never popped.

\$\endgroup\$
1
  • 5
    \$\begingroup\$ Alternatively, {1}g. \$\endgroup\$ Commented Oct 2, 2015 at 19:01
5
\$\begingroup\$

Beam, 2 bytes

There is a few ways of doing this from the very basic

><

to the very basic

>?

and

>|
\$\endgroup\$
1
  • \$\begingroup\$ I just came over here to post this, but then I noticed it in the catalogue snippet. +1 \$\endgroup\$ Commented Oct 2, 2015 at 22:41
5
\$\begingroup\$

C++ 11 template metaprogramming, 58 54 bytes

template<int>struct I{int v=I<1>{}.v;};int a=I<1>{}.v;

C++ helpfully comes packaged with 2 other turing complete languages: the C preprocessor, and template metaprogramming. Note that this does reach a max recursion depth at some point, but the OP clarified that this is okay.

Example run:

g++: internal compiler error: Segmentation fault (program cc1plus)
Please submit a full bug report,
with preprocessed source if appropriate.
See <http://gcc.gnu.org/bugs.html> for instructions.
\$\endgroup\$
5
  • \$\begingroup\$ This is even shorter (41 bytes): template<int I>class A{A<I+1> a;};A<0> a; But unfortunately, it requires the -ftemplate-depth option to be set to something rather high, I used 999999 in this example. \$\endgroup\$
    – iFreilicht
    Commented Oct 16, 2015 at 14:08
  • \$\begingroup\$ And a Preprocessor answer might be impossible unless there's a compiler that allows to set the maximum inclusion recursion depth or number of replacement sweeps per file. \$\endgroup\$
    – iFreilicht
    Commented Oct 16, 2015 at 14:10
  • \$\begingroup\$ @user75200 Next time please add a comment instead of editing someone else's answer when you have a suggestion to golf it further. @user75200 suggested you can remove both int, so it becomes template<int>struct I{v=I<1>{}.v;};a=I<1>{}.v; (46 bytes) \$\endgroup\$ Commented Oct 24, 2017 at 8:13
  • 2
    \$\begingroup\$ @KevinCruijssen/user75200 That doesn't work; types aren't assumed to be int in C++ \$\endgroup\$
    – Justin
    Commented Oct 24, 2017 at 8:18
  • \$\begingroup\$ @Justin Ah ok. I only programmed in C++ once during college, so I barely know anything about it. Simply rejected the edit and placed this comment. :) \$\endgroup\$ Commented Oct 24, 2017 at 8:23
5
\$\begingroup\$

COBOL, 51 bytes

ID DIVISION.PROGRAM-ID.A.PROCEDURE DIVISION.B.GO B.
\$\endgroup\$
1
  • 1
    \$\begingroup\$ procedure division. a. go to a. That's with cobc -frelax-syntax -free -x *filename* but probably counts towards bytes. What COBOL are you using that allows yours to compile with no flags/options? Same for your other COBOL answer. \$\endgroup\$ Commented Mar 2, 2016 at 15:08
5
\$\begingroup\$

Rust, 17 bytes

Didn't see one in rust so:

fn main(){loop{}}

real original and interesting and so different from all the other entries.

\$\endgroup\$
5
  • 1
    \$\begingroup\$ When I try this on the playground, it prints to stderr. \$\endgroup\$ Commented Jan 23, 2018 at 13:10
  • \$\begingroup\$ @BHustus What is it printing to stderr? I'm not getting anything. \$\endgroup\$
    – Liam
    Commented Jan 23, 2018 at 22:23
  • \$\begingroup\$ Besides the standard compilation details, running results in /root/entrypoint.sh: line 7: 6 Killed timeout --signal=KILL ${timeout} "$@" via this link: play.rust-lang.org/… That -might- just be the playground and not the actual compiled product though, I didn't have the chance to test a compiled version. \$\endgroup\$ Commented Jan 24, 2018 at 0:05
  • \$\begingroup\$ @BHustus It's an infinite loop and so the playground kills it after a timeout because they don't want to waste time running my code endlessly. If you run this on a desktop that shouldn't happen. \$\endgroup\$
    – Liam
    Commented Jan 24, 2018 at 2:24
  • \$\begingroup\$ In that case, disregard what I said. \$\endgroup\$ Commented Jan 24, 2018 at 5:18
5
\$\begingroup\$

Half-Broken Car in Heavy Traffic, 5 4 bytes

^ov#

also in 4 bytes:

o
 #
\$\endgroup\$
2
  • \$\begingroup\$ I just took the interpreter for a spin, and somehow I get the feeling the looping is not in the actual code execution, but in the interpreter checking for infinite loops. Can't confirm until I manage to understand this code properly though (I don't think that affects the validity of the answer, but it's interesting...) \$\endgroup\$
    – Sp3000
    Commented Nov 4, 2015 at 13:00
  • 1
    \$\begingroup\$ @Sp3000 Took it for a spin. Nice pun! \$\endgroup\$
    – user63571
    Commented Jan 30, 2017 at 17:29
5
\$\begingroup\$

Commodore Basic, 3 bytes

1R╭

PETSCII substitution: = SHIFT+U, ungolfs to 1 RUN.

Taking advantage of Commodore Basic's shortcut forms and the fact that any immediate-mode command can also be used in a program, this code simply runs itself, forever.

Alternatively, a more thoroughly infinite loop is the immediate-mode command

S|7

(PETSCII: | = SHIFT+Y, ungolfs to SYS 7).

This transfers execution to memory location 0x0007. The BASIC interpreter stores the current search character here; when running the above code, this character is the double-quotation mark with byte value 0x22. Opcode 0x22 is an undocumented HALT opcode, which works by putting the 6510's micro-operation interpreter into an infinite loop. The only way out of this loop is to reset the computer.

\$\endgroup\$
2
  • \$\begingroup\$ How about a note on what R and Shift+U respectively Sand Shift+Y will expand to? And You could submit a 6510 assembler program. \$\endgroup\$
    – Titus
    Commented Dec 1, 2016 at 0:36
  • \$\begingroup\$ On the Commodore 64 and VIC-20 you can also use 0 GOTO - if you do not specify a number then GOTO assumes that you mean GOTO 0. As Commodore BASIC on the C64 and VIC are recycled from earlier CBM/PET machines, this may also work on those computers. It does not work on the C128 in native mode though. \$\endgroup\$ Commented Jan 26, 2017 at 11:36
5
\$\begingroup\$

Tcl/Tk, 0 bytes

Execute any empty file with the wish interpreter instead of tclsh.

\$\endgroup\$
5
\$\begingroup\$

TI-BASIC, 2 bytes

If recursion is allowed (is it a loop?)

prgmA

Runs a program named 'A', hence the program must be named the same. Some research revealed that prgm is 1 byte, plus 1 byte for A

Runs out of memory pretty quickly, but that doesn't seem to be addressed above.

\$\endgroup\$
8
  • 1
    \$\begingroup\$ : is the mandatory beginning of each line, and I believe that isn't counted. Also, the title shouldn't be counted. Do you count a .js file name into the byte count? I'll look into the prgm token, though it's a single command. \$\endgroup\$ Commented Oct 3, 2015 at 0:27
  • \$\begingroup\$ In this case, however, the actual title is irrelevant as long as it matches the command. \$\endgroup\$ Commented Oct 3, 2015 at 0:39
  • 1
    \$\begingroup\$ Isn't it three bytes: 1 for the A in the program name \$\endgroup\$ Commented Jul 31, 2017 at 21:44
  • 4
    \$\begingroup\$ Why do people always add : to the start of each line? It's just a part of the editor, not the actual code. \$\endgroup\$
    – 12Me21
    Commented Feb 12, 2018 at 15:23
  • 1
    \$\begingroup\$ @raddish0 "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" \$\endgroup\$ Commented Jun 28, 2020 at 21:26
5
\$\begingroup\$

x86-16 Assembly, IBM PC DOS, 2 bytes

There's quite a few machine code answers, but thought I'd contribute a few different takes.

56    PUSH SI    ; push 100H onto stack
C3    RET        ; pop stack and jump to address (PUSH SI)

On DOS when a program is started the SI register contains the starting address of the program (generally 100H). Push that onto the stack and execute a RET which will pop the stack and jump to that address. Big ol' loop.


x86-16 Assembly, 1 byte

F4   HLT         ; halt the processor and wait for signal

Okay, so this may depend a little on your definition of infinite loop. The HLT instruction (specifically in 8086 real mode) puts the processor in HALT state and awaits a signal in the form of BINIT#, INIT#, RESET# or interrupt (ref). While it's not technically executing our code, it is in a microcode loop of sorts waiting for one of those signals.


Motorola 6800, 2 bytes

9D DD   HCF      ; halt and catch fire

From Wikipedia:

When this instruction is run the only way to see what it is doing is with an oscilloscope. From the user's point of view the machine halts and defies most attempts to get it restarted. Those persons with indicator lamps on the address bus will see that the processor begins to read all of the memory, sequentially, very quickly. In effect, the address bus turns into a 16 bit counter. However, the processor takes no notice of what it is reading… it just reads.

\$\endgroup\$
4
\$\begingroup\$

MUMPS, 1 byte

f

This is the equivalent of for ( ; ; ) ; in C-like languages. It runs from the prompt as is, though, and does not need to be wrapped in a function declaration or any such thing.

\$\endgroup\$
4
\$\begingroup\$

GNU dc, 6 bytes

[dx]dx

Tail recursion FTW, which GNU dc supports. Others might not.

\$\endgroup\$
3
  • \$\begingroup\$ That's my length 6 dc snippet :) But on my machine it just crashes. Is that normal? \$\endgroup\$
    – daniero
    Commented Oct 2, 2015 at 18:27
  • \$\begingroup\$ Which machine do you have? (and which dc?). I'm running GNU dc on Linux, which supports infinite tail recursion. I think possibly other dcs don't support any kind of tail recursion, and end up crashing with a stack overflow. \$\endgroup\$ Commented Oct 2, 2015 at 20:05
  • \$\begingroup\$ A mac, using the pre-installed dc. It says dc (GNU bc 1.06) 1.3. I see that it works on a Linux box with the slightly newer version (1.3.95) \$\endgroup\$
    – daniero
    Commented Oct 2, 2015 at 20:14
4
\$\begingroup\$

MSM, 2 bytes

ee

Almost all 2 character strings will work, even two spaces, just don't use any of the following 6 commands :,/.?'.

\$\endgroup\$
4
\$\begingroup\$

Javascript (8 bytes)

for(;;);

Edit courtody of @KritixiLithos

Javascript (10 bytes)

while(1){}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ Try for(;;); It has 8 bytes. \$\endgroup\$
    – user41805
    Commented Oct 3, 2015 at 9:29
  • \$\begingroup\$ @KritixiLithos I forgot that javascript for loops are basically infinite if used wrong. I'm way too used to languages like python which eventually stop for loops. Very clever :) \$\endgroup\$
    – Daffy
    Commented Oct 4, 2015 at 10:26
  • \$\begingroup\$ Although, one can make an infinite for loop in python. \$\endgroup\$ Commented May 12, 2017 at 23:11
4
\$\begingroup\$

Scheme, 12 bytes

A tail-recursive infinite loop seems most appropriate for scheme :-)

(let l()(l))

even though (do(())()) (the CL variant of which is due to @JoshuaTaylor) would be 2 bytes shorter.

\$\endgroup\$
4
\$\begingroup\$

z80 Machine Code, 1 byte

c7       ; RST 00h

Or if assuming the code starts at 0000h is cheating, two bytes:

18 fe    ; JR -2

These solutions make no assumptions about the rest of the environment's RAM. If it's filled with zero bytes, we are just spinning through NOPs forever, so we could have a 0-byte solution. (Thanks to Thomas Kwa for pointing this out.)

\$\endgroup\$
3
  • \$\begingroup\$ Good point; I've written a note about it. \$\endgroup\$
    – lynn
    Commented Oct 4, 2015 at 19:20
  • 1
    \$\begingroup\$ For special fun, fill RAM with 0xDD (or 0xFD). Or maybe this isn't an infinite loop, because it's just one infinitely long opcode. \$\endgroup\$ Commented Oct 6, 2015 at 16:36
  • \$\begingroup\$ 1Byte = 76 ; Halt codegolf.stackexchange.com/a/166100/80745 \$\endgroup\$
    – mazzy
    Commented Jun 4, 2018 at 10:01
4
\$\begingroup\$

Fortran, 11 bytes

It is not very creative, but here is the shortest I found:

1goto 1
end

I am pretty sure this is not standards compliant, but it compiles with ifort.

\$\endgroup\$
4
\$\begingroup\$

3var, 2 bytes

{}

To quote the docs:

{   Starts a loop which repeats forever
}   Ends a loop which repeats forever
\$\endgroup\$
4
\$\begingroup\$

R, 8 bytes

repeat{}

I believe this is the shortest way to make a loop that won't stop. We would need an infinite length list to use a for loop and while(T) is longer than repeat.

\$\endgroup\$
4
  • \$\begingroup\$ I thought I had, but it sure as hell doesn't work -- dunno what I did. Sorry about that. \$\endgroup\$ Commented Oct 13, 2017 at 18:54
  • 2
    \$\begingroup\$ +1 : This or equivalently repeat 1 (or repeat x with x being any valid single character expression) \$\endgroup\$
    – digEmAll
    Commented Jun 4, 2018 at 8:11
  • \$\begingroup\$ @digEmAll doesn’t repeat 1 output something? \$\endgroup\$
    – JayCe
    Commented Jun 25, 2018 at 1:43
  • \$\begingroup\$ @JayCe: I also thought so, but actually it doesn't... \$\endgroup\$
    – digEmAll
    Commented Jun 25, 2018 at 6:25
4
\$\begingroup\$

NASM/YASM x86 assembly, 4 bytes

ja $

$ is the address of the current instruction, and ja jumps there if the carry and zero flags are both unset. (i.e. the Above condition is true.) This is the case in x86-64 Linux at process startup.

ja$ just defines a symbol, instead of being an instruction, so the space is not optional. I did test that this works without a trailing newline, so it really is 4 bytes.

Assemble/link with

$ yasm -felf64 foo.asm && ld -o foo foo.o
ld: warning: cannot find entry symbol _start; defaulting to 0000000000400080

The x86-64 ABI used by Linux doesn't guarantee anything about the state of registers at process startup, but Linux's actual implementation zeroes all the registers other than RSP for a newly-execed process. EFLAGS=0x202 [ IF ], so ja (jump if Above) does jump, because the carry and zero flags aren't set. jg (ZF=0 and SF=0) would also work. Other OSes that initialize flags differently might be able to use one of the other one-letter conditions that require a flag bit to be set: jz, jl, jc, jp, js.

Using ja instead of jmp (unconditional jump) makes the source one byte shorter, but the binary is the same size (2 bytes: one opcode byte, one rel8 displacement, for a total size of 344 bytes for a stripped ELF64 binary. See casey's answer for a 45 byte ELF executable if you're interested in small binary size rather than small source size.)

\$\endgroup\$
4
\$\begingroup\$

AT&T (PDP-11) Syntax Assembly: 4 bytes

br .

PDP-11 UNIX A.OUT binary output: 24 18 bytes

0000000  000407 000002 000000 000000 000000 000000 000000 000000
0000020  000777 000000 000000 000004
0000030

This is the output produced by the assembler. As the sizes in the header show, the last three words are not necessary, it can be cut down to the first 18 bytes.

Some modern assemblers do not support the br instruction, so it would be five bytes for jmp .. And executable headers are generally much bigger these days.

Linux x86-64 binary output, after strip: 336 bytes

Now, OSX's assembler is much more strict. You must have a symbol (by default start, but here I use f) for the entry point, which balloons the size of the source. It also requires a newline at the end of the file.

Mac OS X x86-64 Assembly: 17 bytes

.globl f
f:jmp f

Mac OS Mach-O Binary Output: 4200 bytes

\$\endgroup\$
5
  • 3
    \$\begingroup\$ You can get smaller binary output if you golf the ELF header in Linux: see codegolf.stackexchange.com/a/59479/19694 \$\endgroup\$
    – casey
    Commented Oct 3, 2015 at 3:35
  • \$\begingroup\$ What machine is br . for? x86? Which assembler? GNU as rejects it for x86-64. In any case, I posted a 4-byte x86 YASM source, which assembles and links into a complete working infinite loop program on Linux: ja $. GNU ld defaults to 0x0400080 if it can't find a _start symbol, so this really is a complete program. \$\endgroup\$ Commented Oct 6, 2015 at 21:07
  • \$\begingroup\$ @PeterCordes PDP-11 - and I assume also VAX, though I haven't had a chance to test it. It's common for older assemblers to use separate mnemonics for short jump instructions. The PDP-11 instruction contains the offset within the instruction word, with a range of even values from -64 to +62. \$\endgroup\$
    – Random832
    Commented Oct 6, 2015 at 21:08
  • \$\begingroup\$ @Random832: could you update your answer, then? "AT&T syntax" doesn't specify a machine. For example, there is an i386/amd64 flavour of "AT&T syntax", used by the GNU tools by default. add $16, %rsp, for example. \$\endgroup\$ Commented Oct 6, 2015 at 21:10
  • \$\begingroup\$ My answer goes into detail on the source required to make a usable x86-64 program on GNU/Linux and Mac OSX. By "AT&T" I meant the actual original assembler produced by AT&T, whose syntax is imitated by these other assemblers. \$\endgroup\$
    – Random832
    Commented Oct 6, 2015 at 21:11
4
\$\begingroup\$

pb, 8 bytes

In pb, the shortest possible infinite loop is 8 bytes long. In fact, there are sixty 8 byte infinite loops, none of which produce output! (Unless you're running in watch mode, which is intended for debugging, no pb programs produce output until they halt. However, even if one of these did eventually halt, no output would have been produced.) Here are the sixty shortest infinite loops, in alphabetical order:

w[B!1]{}
w[B!2]{}
w[B!3]{}
w[B!4]{}
w[B!5]{}
w[B!6]{}
w[B!7]{}
w[B!8]{}
w[B!9]{}
w[B=0]{}
w[C!1]{}
w[C!2]{}
w[C!3]{}
w[C!4]{}
w[C!5]{}
w[C!6]{}
w[C!7]{}
w[C!8]{}
w[C!9]{}
w[C=0]{}
w[P!1]{}
w[P!2]{}
w[P!3]{}
w[P!4]{}
w[P!5]{}
w[P!6]{}
w[P!7]{}
w[P!8]{}
w[P!9]{}
w[P=0]{}
w[T!1]{}
w[T!2]{}
w[T!3]{}
w[T!4]{}
w[T!5]{}
w[T!6]{}
w[T!7]{}
w[T!8]{}
w[T!9]{}
w[T=0]{}
w[X!1]{}
w[X!2]{}
w[X!3]{}
w[X!4]{}
w[X!5]{}
w[X!6]{}
w[X!7]{}
w[X!8]{}
w[X!9]{}
w[X=0]{}
w[Y!1]{}
w[Y!2]{}
w[Y!3]{}
w[Y!4]{}
w[Y!5]{}
w[Y!6]{}
w[Y!7]{}
w[Y!8]{}
w[Y!9]{}
w[Y=0]{}

These all follow a simple pattern. w is a while loop, pb's only looping or branching instruction. Inside the square brackets is the condition, which is two expressions separated by ! or =. To understand what this means, imagine an extra = just before the second expression. In the same way that you understand 2+2==4 to be true and 10!=5*2 to be false, 2+2=4 and 10!5*2 are true and false in pb. A while loop is executed until the condition becomes false. Finally, there is a pair of curly braces containing pb code. In this case, there's no code to be run, so they are empty.

The important thing here is the condition. pb has six variables, all for different purposes. They are:

B - The value of the character under the brush
C - The colour of the character under the brush (from a lookup table, the important thing being that white = 0)
P - The current colour that the brush is set to output in (same lookup table)
T - Set by the programmer, initialized to 0
X - X position of the brush
Y - Y position of the brush

The brush starts at (0, 0) on a canvas that is entirely initialized to white null bytes. This means that all of the variables start out being equal to 0.

These sixty programs fall into two categories: 10 loops that are executed until a variable (equivalent to 0) stops being zero, and 50 loops that are executed until a variable (equivalent to 0) becomes a specific non-zero number. An infinite number of programs can be written that fall into that second group, but only 50 are the same length as the 10 in the first one.

\$\endgroup\$
4
\$\begingroup\$

ArnoldC, 61 bytes

IT'S SHOWTIME
STICK AROUND 1
CHILL
YOU HAVE BEEN TERMINATED

Ironic how the program never actually terminates, even though the last line says "YOU HAVE BEEN TERMINATED."

\$\endgroup\$
4
\$\begingroup\$

Brian & Chuck, 7 bytes

#{?
#{?

The # could be replaced by any other characters except null-bytes or underscores.

The idea is fairly simple:

  • Brian moves Chuck's instruction pointer to the start ({) and hands control over to him (?).
  • Chuck moves Brian's instruction pointer to the start ({) and hands control over to him (?).
  • Repeat.
\$\endgroup\$
4
\$\begingroup\$

Seed, 2 bytes

0 

(note the trailing space character)

Any seed program consists out of 2 instructions, seperated by a space; The length of the Befunge program it will output and the seed which will generate that program.
Seeing how we need a Befunge program of length 0, we can create a Seed program with an empty 2nd instruction.

The Seed program 0 will output an empty Befunge program, which will run forever.

Interesting to note is that the Python compiler on the Seed esolang page is erroneous.
To create a Befunge program of length 0, any seed will do. That includes an empty seed. To stick to the spec however, the space after 0 is not omitted.

That being said, this is the world's shortest Seed program, and also the easiest to reverse engineer :-)

\$\endgroup\$
4
\$\begingroup\$

Aubergine, 6 bytes

:aa=ia

:aa is a no-op. =ia sets the IP to its own location.

\$\endgroup\$
1
  • \$\begingroup\$ Likewise, aaaiii is the shortest for Purple BUT -i3 is the shortest for UberGenes \$\endgroup\$
    – quintopia
    Commented Dec 31, 2015 at 6:53
1 2
3
4 5
20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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