Your task is to write a full program or function that takes no input and runs any type of loop (while, for, foreach, do, do-while, do-loop, goto, recursion, etc) that will end in causing an error, which means that the program must stop itself running and exit.


  1. The error must be a run-time error, unhandled exception, or anything that makes the program end itself.
  2. The error must produce the stop and exit from the program without calling explicitly exit; (or equivalent) at some point.
  3. Messages like Warning:, Notice:, etc, that do not cause the program to end itself are not valid. For example in PHP divisions by zero produces a Warning message but the program will not stop and will still run, this is not a valid answer.
  4. The loop must run at least one full cycle. In other words the error can happen starting at the second cycle and further. This is to avoid to cause the error using incorrect code syntax: the code must be syntactically correct.
  5. The loop can be even infinite (example for(;;);) if it respects the above said rules, but must take no longer than 2 minutes to end itself in a run-time error.
  6. Recursion without Tail Call Optimization is invalid (1,2).
  7. This is so the shortest code wins.
  8. Standard loopholes are forbidden.

C# example (test online):

using System;
public class Program {
    public static void Main() {
        int i;
        int[] n;
        n = new int[5];
        for(i=0; i<7; i++) {
            n[i] = i;


Run-time exception (line 9): Index was outside the bounds of the array.

Stack Trace:

[System.IndexOutOfRangeException: Index was outside the bounds of the array.]
  at Program.Main(): line 9


var QUESTION_ID=104323,OVERRIDE_USER=59718;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important;font-family:Arial,Helvetica; font-size:12px}#answer-list,#language-list{padding:10px;width:290px;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="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><div id="language-list"> <h2>Winners 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><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>

Thanks to Martin Ender for the Leaderboard Snippet

  • \$\begingroup\$ Just to be clear, recursion without TCO can be used as long as the error does not have to do with too much recursion, correct? (For example, a recursive function that errors on the second recursion) \$\endgroup\$ Commented Dec 23, 2016 at 22:06
  • \$\begingroup\$ @ETHproductions It was suggested by Dennis in chat: "It might be difficult to decide if a full cycle has completed in this case [of recursion]. Tail recursion kinda fits the bill, but only TCO does actually complete a cycle if execution is aborted by an error. [...] I'd say recursion without TCO is invalid." \$\endgroup\$
    – Mario
    Commented Dec 23, 2016 at 22:13
  • 1
    \$\begingroup\$ @Hedi Here's my humble opinion (not the OP): All entries must complete one full cycle, meaning they must enter a second cycle; this means that at least one statement is run a second time. Since the order of execution in your example is a, b, d, c, b, d, c, ..., b is the start of the cycle, and must be run at least a second time. \$\endgroup\$ Commented Dec 24, 2016 at 1:20
  • 3
    \$\begingroup\$ I don't want to start any trouble but since the program (of function for that matter) is not supposed to be taking any input, all recursive solutions that have a parameter are invalid because a parameter is input. \$\endgroup\$
    – BrainStone
    Commented Dec 25, 2016 at 11:43
  • 3
    \$\begingroup\$ Voting to close because the requirements for what counts as a loop and what counts as what part of the loop are unobservable. This could sort of go either way, but I think it's vague enough that it could (and from what I've seen, has) cause disagreement about the correct interpretation. \$\endgroup\$ Commented Jun 16, 2021 at 3:22

103 Answers 103


Python, 16 bytes

The non-interesting 0 division approach:

for x in 1,0:x/x

The first iteration computes 1 / 1, which works fine. The second iteration tries to compute 0 / 0, resulting in a ZeroDivisionError being thrown.

17 bytes (personal favourite)

while i:del i

Initially, i=1 which is truthy, so the loop is entered.

The first time the loop is run, the variable i is deleted.

This means that, the second time, i is no longer a variable and therefore its evaluation fails with NameError: name 'i' is not defined.

Another 15 byte solution would be def _():_() (newline) _(), because Python does not optimize tail recursion. However, this violates rule #6.

  • \$\begingroup\$ The 17 bytes solution also works if you replace while i with while 1 because it tries to delete i again; \$\endgroup\$ Commented Dec 24, 2016 at 17:56
  • 2
    \$\begingroup\$ @user6245072 yep, both snippets can be trivially modified for lots of working solutions \$\endgroup\$
    – FlipTack
    Commented Dec 24, 2016 at 18:11
  • 1
    \$\begingroup\$ You can use your del trick with a built-in to shave off a few more: while 1:del id. \$\endgroup\$
    – DSM
    Commented Dec 24, 2016 at 21:02
  • \$\begingroup\$ @DSM: del id doesn't work. You can't delete builtins that way. \$\endgroup\$ Commented Dec 28, 2016 at 3:34
  • \$\begingroup\$ Would for i in[0]:i/i work? \$\endgroup\$ Commented Mar 8, 2022 at 14:52

MATL, 5 1 byte

Idea taken from @MartinEnder's CJam answer


Try it online!

`    % Do...while loop
     % Implicit end. The loop continues if the top of the stack is true.
     % After the first iteration, since the stack is empty, the program 
     % implicitly tries to take some non-existing input, and finishes
     % with an error

Old version


Try it online!

2:   % Push [1 2]
t    % Duplicate
"    % For each (i.e. do the following twice)
  x  %   Delete top of the stack. Works the first time. The second it tries to
     %   implicitly take some non-existing input, and finishes with an error
  • 3
    \$\begingroup\$ Works offline as well. No input means you can assume empty input. \$\endgroup\$
    – Dennis
    Commented Dec 23, 2016 at 22:29
  • \$\begingroup\$ @Dennis Hm the offline program will keep waiting for user input. Input is interactive, i.e. requested as needed in the offline version. So the program will wait indefinitely. Not sure that counts? \$\endgroup\$
    – Luis Mendo
    Commented Dec 23, 2016 at 22:32
  • 1
    \$\begingroup\$ Not exactly sure how MATL works internally, but if you execute it in an environment incapable of requesting input (such as TIO's backend), it won't be able to get any input. Also, pressing Ctrl-D or the OS-dependent equivalent should be allowed to send empty input. \$\endgroup\$
    – Dennis
    Commented Dec 23, 2016 at 22:34

Jelly, 3 2 bytes


Kills itself by running out of memory. Locally does so after ~100 seconds.

Try it online! (death certificate in Debug drawer)

How it works

Ṿß  Main link. Argument: x. Implicit first argument: 0

Ṿ   Uneval; yield a string representation of x.
 ß  Recursively call the main link.
    Jelly uses TCO, so the first cycle finishes successfully before entering
    the next one.

The first few iterations yield:


After that, it gets real ugly, real fast.

  • \$\begingroup\$ What is jelly's memory limits? \$\endgroup\$
    – tuskiomi
    Commented Dec 24, 2016 at 0:09
  • \$\begingroup\$ Jelly doesn't have an explicit memory limit, so whatever Python can address. Memory usage doubles with each iteration though, so this should exhaust all available memory rather quickly. \$\endgroup\$
    – Dennis
    Commented Dec 24, 2016 at 0:40
  • 33
    \$\begingroup\$ So every 2 years, we'll be able to execute another iteration \$\endgroup\$
    – tuskiomi
    Commented Dec 24, 2016 at 0:43
  • \$\begingroup\$ So will fail condition #5 on slow machine with lots of RAM? \$\endgroup\$ Commented Dec 27, 2016 at 22:18
  • 1
    \$\begingroup\$ @MadPhysicist That is correct. This is a inherent problem with time limits though. Compliance depends very much on which machine the program is run. \$\endgroup\$
    – Dennis
    Commented Dec 27, 2016 at 22:22

V, 2 bytes


Try it online!

This is the perfect challenge for V because I already do that all the time! In fact, V doesn't even have any conditionals, it only has functions that break on an error. In this case, the ò means "repeat forever" and the l means "move right".

In an empty buffer (no input) this will break on the first pass and produce no output. If there is input, it will break once we move post the last character of input, and output all of the input (making this also a cat program)

  • 3
    \$\begingroup\$ Wait, l means "move right"? Not "move left"? \$\endgroup\$ Commented Dec 24, 2016 at 3:50
  • 1
    \$\begingroup\$ @ConorO'Brien yep. There's actually some good historical reasons for this. \$\endgroup\$
    – DJMcMayhem
    Commented Dec 24, 2016 at 3:53
  • 4
    \$\begingroup\$ The challenge requires answers to crash on the second iteration or later, not on the first iteration. \$\endgroup\$ Commented Dec 26, 2016 at 13:44

JavaScript (ES6), 13 bytes


This is a recursive function that runs fine once, then throws ReferenceError: a is not defined and quits.

Here's a 15-byte non-ES6 version:


This runs fine once, then throws TypeError: i is undefined and quits.


GNU sed, 15 13 5 bytes

-2 Thanks to seshoumara
-8 Thanks to zeppelin

  1. Appends a newline and the hold space to the pattern space.
  2. Appends a newline and the pattern space to the hold space.
  3. Deletes up to the first newline and starts over.

This quickly runs out of memory:

$ time (echo|sed 'H;G;D')
sed: couldn't re-allocate memory

real    0m1.580s
user    0m0.545s
sys     0m1.012s
  • \$\begingroup\$ Hi, how about s:a\?:&a:g? It is 1 byte less and doubles the pattern size per iteration as well. \$\endgroup\$
    – seshoumara
    Commented Feb 3, 2017 at 15:48
  • \$\begingroup\$ @seshoumara I don't think that'll match anything when the pattern space is empty, so it'll never make the first replacement. \$\endgroup\$
    – Riley
    Commented Feb 3, 2017 at 15:54
  • \$\begingroup\$ @seshoumara echo -n | sed 's:a\?:&a:g' and got no output. It would be the same as sed 's::a:' which wouldn't match anything. \$\endgroup\$
    – Riley
    Commented Feb 3, 2017 at 16:25
  • \$\begingroup\$ With echo -n absolutely nothing gets passed to sed, but sed can't start without input by design. Check this meta link to see that echo|sed is the accepted way to start sed for challenges invoking a no input rule. \$\endgroup\$
    – seshoumara
    Commented Feb 3, 2017 at 16:33
  • \$\begingroup\$ @seshoumara I thought it would still give it an empty string. That seems to work then. Thanks! \$\endgroup\$
    – Riley
    Commented Feb 3, 2017 at 16:39

Bash 4.2, 22 bytes

exec $0 $@ $[2**$#%-1]

Doesn't work in TIO because it has Bash 4.3, and the bug I'm relying on was finally fixed.


$ xxd -c 22 -g 22 self-destruct
0000000: 6578656320243020244020245b322a2a2423252d315d  exec $0 $@ $[2**$#%-1]
$ ./self-destruct
Floating point exception

This crashes once the program tries to compute 263 mod -1, which crashes in Bash 4.2 and older versions due to a known bug.


Befunge-93, 3 bytes (possibly 1 or 0)


Try it online!

On the first iteration of the loop, the stack is empty, which is the equivalent of all zeros. The ! (not) operation thus converts the stack top to 1, and the % (modulo) operation calculates 0 mod 1, leaving 0. The next ! operation converts that 0 to a 1 before the program counter wraps around and begins the loop again.

On the second iteration, the first ! operations converts the 1 that is now at the top of the stack to a 0. The % operation then calculates 0 mod 0, which produces a division by zero error on the reference interpreter, and thus terminates the program.

There's also the more boring 1 byte answer, although I'm not sure if this is considered valid.


Try it online!

This " command starts a string, thus every space on the rest of the line is pushed onto the stack until the program counter wraps around and encounters the " again closing the string. It'll then need to wrap around a second time to repeat the process starting another string and pushing another 79 spaces onto the stack. Eventually this will either run out of memory (the reference interpreter behaviour) or produce a stack overflow.

Now if you want to really push the rules there's also technically a zero byte solution.

If you take this ruling to mean that any interpreter defines the language (as many here do), then we can assume for the moment that the Befunge language is defined by this interpreter. And one of the "features" of that interpreter is that it pushes an Undefined value onto the stack for each loop of the playfield when executing a blank program. Given enough time it will eventually run out of memory.

How fast that happens will depend on the speed of the computer, the available memory, and the browser being used. On my machine I found that Microsoft Edge worked best, but even then it was "only" using 500MB after two minutes. It wasn't until around the fifteen minute mark (with several gigabytes used) that Edge decided to kill the process and refresh the tab. So it's unlikely to make it under the two minute time limit, but with the right conditions that wouldn't necessarily be out of the question.


PHP, 22 21 20 18 bytes

This relies on PHP allowing one to give a function name to a variable and try to run it.

This simply concatenate the name of the pi function twice. This kills PHP with a Fatal Error: Uncaught Error: Call to undefined function pipi() in [...][...].


This works similar to my old answer.

Old answer, 20 bytes

PHP allows you to increment characters, using the increment operator. It only works on the a-z range, but is enough.


I believe this fulfills all the required points and the loop does run once.

You can see if because you will get the error Fatal error: Function name must be a string.

How this works, step by step:

  • Assign pi to $x.
    Since pi is being used as a constant, PHP will check if exists.
    Since it doesn't, PHP shows a warning saying Use of undefined constant pi - assumed 'pi' (Basically: since the constant doesn't exist, it is assumed to be a string)
  • Loop the first time
    • Run the function $x().
      Since $x has the value pi, it will run the function pi().
  • Store the value in $x.
    $x now has π, instead of pi
  • Loop for the second time
    • Run the function $x().
      Since $x has π, it will run the function 3.14159...().
    • π isn't a string, killing the program at this point with a Fatal Error.

Thanks to @Titus for finding the pi() function, saving me 1 byte!

  • \$\begingroup\$ Nice one, but I don't think it's valid. It doesn't really run the loop once. You increment $x to abt before the loop body runs. You could fix that by incrementing after the loop. \$\endgroup\$
    – aross
    Commented Dec 27, 2016 at 14:56
  • \$\begingroup\$ I thought of a different approach \$\endgroup\$
    – aross
    Commented Dec 27, 2016 at 15:22
  • \$\begingroup\$ @aross Duh, You're right, it wasn't valid. The increment is in the wrong place. It is working as it should now. You can try to run for($x=abs;;++$x)echo$x,$x(); to test. It should show abs0abt Fatal error[...]. Or similar. \$\endgroup\$ Commented Dec 28, 2016 at 9:52
  • 1
    \$\begingroup\$ You could use pi instead of abs. That doesn´t even yield a warning before it throws the fatal. \$\endgroup\$
    – Titus
    Commented Jan 9, 2017 at 16:39
  • \$\begingroup\$ @Titus I completelly forgot about that function! I know that the function _ is defined in some systems, but is unreliable. But thank you for finding that! \$\endgroup\$ Commented Jan 9, 2017 at 18:36

C, 21 bytes


Here i is guaranteed to start off as 0.

It can be confirmed that this runs once like so:


Which, on my machine, results in:

llama@llama:...code/c/ppcg104323loop$ ./a.out 
zsh: floating point exception (core dumped)  ./a.out

The shortest recursive solution I can find is 22 bytes:


gcc only does tail call elimination at -O2 or higher, at which point we need to call a function like puts to prevent the entire thing from being optimized away. Confirmation that this works:

llama@llama:...code/c/ppcg104323loop$ cat loop.c       
llama@llama:...code/c/ppcg104323loop$ gcc -O2 -S loop.c 2>/dev/null
llama@llama:...code/c/ppcg104323loop$ grep call loop.s
    call    puts
    call    f

The following is a full program, which assumes that it is called with no command line arguments, at 22 bytes:


which is equivalent to the function of the same length:

  • \$\begingroup\$ Is a function like this treated like main? If it is, the first argument is the length of the argument list (which is 1, the name that was used to call it). \$\endgroup\$
    – Riley
    Commented Dec 24, 2016 at 0:40
  • \$\begingroup\$ Or, the argument register still has the value that was there from main getting called. \$\endgroup\$
    – Riley
    Commented Dec 24, 2016 at 0:47
  • \$\begingroup\$ @Riley Ahh, the latter theory appears to be the case, as evidenced by the fact that the number increases as command line arguments are added. Thanks for the insight! \$\endgroup\$
    – Doorknob
    Commented Dec 24, 2016 at 1:02
  • \$\begingroup\$ I wasn't sure how you were calling it in my first guess, but i should be the same as the first argument to the function that calls f. \$\endgroup\$
    – Riley
    Commented Dec 24, 2016 at 1:08
  • \$\begingroup\$ Yep, tio \$\endgroup\$
    – Riley
    Commented Dec 24, 2016 at 1:11

R, 22 25 22 20 18 bytes

Edit: Thanks to @Mego for pointing out that R does not support tail call optimization.

Edit4: Found an even shorter solution which simple yet quite intricate.


The answer uses the builtin boolean truthy variable, T which is decremented indefinitely in the repeating loop. The function ls() is called each iteration which lists all objects in the current environment. However, the first argument name specifies from which environment from which to list objects. From the R-documentation we find that:

The name argument can specify the environment from which object names are taken in one of several forms: as an integer (the position in the search list); as the character string name of an element in the search list; or as an explicit environment (including using sys.frame to access the currently active function calls).

This principally means that in the first iteration we run ls(-1) which would return character(0) (standard when trying to access the non-existent everything-except-the-first element of any character type object). During the second iteration, T is decremented by two and we subsequently call ls(-3) which in turn returns the error:

Error in as.environment(pos) : invalid 'pos' argument

This is because we try to list everything-except-the-third element but the local environment only contains the variable T at this point (as such, ls() would return a list of length 1 at this iteration) and an error is returned.

  • 1
    \$\begingroup\$ That doesn't sound like the recursion is done with tail call optimization, if there is a recursion limit. \$\endgroup\$
    – user45941
    Commented Dec 23, 2016 at 23:15
  • \$\begingroup\$ @Mego After some digging around I found out that R does indeed not support tail call optimization so this answer is not valid (never heard of the concept before). Will change to a valid answer in a moment. \$\endgroup\$
    – Billywob
    Commented Dec 23, 2016 at 23:22

FALSE, 8 bytes

I really like this language.


This pushes a 1, then [$][.]# loops while $ is true (duplicate top of stack) and (.) outputs it. This interpreter crashes after the single 1 is printed (evidence of the loop running at least once.) It seems to be a bug in this interpreter. The following 9-byte program should work in all compliant interpreters:

  • \$\begingroup\$ You should also try DUP, which is basically a superset of FALSE. That's what I used to make RETURN. \$\endgroup\$ Commented Dec 24, 2016 at 3:04
  • \$\begingroup\$ @MamaFunRoll oh yeah, I forgot that you made RETURN! I gotta try that one. :D \$\endgroup\$ Commented Dec 24, 2016 at 3:12
  • \$\begingroup\$ @MamaFunRoll I love DUP, I just wrote a DUP interpreter and I’m playing around with it. \$\endgroup\$
    – M L
    Commented Dec 27, 2016 at 18:20
  • \$\begingroup\$ @ConnorO'Brien: I would say that your first solution should crash any interpreter. I just made a debug run with my own interpreter, and it’s obvious that the first . empties the data stack, while in the second loop $ tries to duplicate the top element of the empty stack, which should lead to an error (well, my interpreter does). The second version should not be valid because it does not even finish the first loop because it already tries to access the empty stack prematurely. \$\endgroup\$
    – M L
    Commented Dec 27, 2016 at 18:36
  • \$\begingroup\$ For your second example, Here’s a full colored debug Dump of my DUP interpreter. it’s obvious once you see how the data stack (ds) and the return stack (rs) work, the latter not being transparent in FALSE, though. \$\endgroup\$
    – M L
    Commented Dec 27, 2016 at 19:00

QBasic, 17 bytes

This code is very weird.


How it works

In QBasic, variables are preinitialized. A regular variable without any type suffix, like i here, is preinitialized to zero.

Except if you try to subscript into that variable like an array... in which case, it's an array of 11 zeros.*

On the first time through the loop, therefore, i is 0 and a is an array. a(i) gives the zeroth element of the array (which is 0). All well and good. We set i to 11 and loop. But now 11 is not a valid index for the array a, and the program halts with Subscript out of range.

A 19-byte version that better shows what's going on:


This will print 0 eleven times before erroring.

* Conceptually, it's a 10-element array. Most things in QBasic are 1-indexed, but arrays aren't, possibly for implementation reasons. To make things work as expected for programmers, QBasic throws in an extra entry so you can use indices 1 to 10. Index 0, however, is still perfectly accessible. Go figure.

  • \$\begingroup\$ QBasic and arrays, where does the fun stop! \$\endgroup\$
    – steenbergh
    Commented Dec 24, 2016 at 9:59
  • \$\begingroup\$ Since the error doesn't have to be on the second loop, couldn't you do i=1+a(i)? \$\endgroup\$
    – Quelklef
    Commented Dec 24, 2016 at 15:40
  • \$\begingroup\$ @Quelklef No, you'd have to do i=i+1+a(i). Otherwise the index never gets above 1, which isn't an error. \$\endgroup\$
    – DLosc
    Commented Dec 24, 2016 at 19:31
  • \$\begingroup\$ @DLosc Oh, you're right. \$\endgroup\$
    – Quelklef
    Commented Dec 25, 2016 at 21:25

MATLAB, 18 bytes

This can be run as a script:

for j=1:2;j(j);end

The first iteration is fine, since j(1) is just 1. The second iteration crashes with an array out of bounds error, as j(2) exceeds the dimensions of j, which is a 1x1 array.

This also can be run as a script, but it only works the first time you run it. Still, it's a hilarious enough abuse of MATLAB's predefined constants that I thought I'd include it. It's also 18 bytes.

while i/i;i={};end

When run in a workspace that the variable i hasn't been defined in yet, this assumes i is the imaginary unit, so i/i = 1. In the first loop, the assignment i={} creates an empty cell array called i. On the second iteration, the loop exits with "Undefined operator '/' for input arguments of type 'cell'."

  • \$\begingroup\$ Both of those are awesome! You probably know this, but j(2) would normally give a 2-by-2 matrix with 0+1i \$\endgroup\$ Commented Apr 10, 2017 at 10:18
  • \$\begingroup\$ Thanks! That's true in Octave but not in MATLAB I think \$\endgroup\$
    – hwm
    Commented Apr 11, 2017 at 20:25

Perl 6, 13 bytes

loop {5[$++]}

Indexes an integer literal in an infinite loop.
Relies on fact that on scalar values, the array indexing syntax can be used with index 0 (returning the value itself), but throws an Index out of range error for any other index.


CJam, 4 bytes


Try it online!

The first iteration of the empty {}g loop pops the 1, which tells it to continue. The second iteration tries to pop another conditional, but the stack is empty, so the program crashes.


Haskell, 15 bytes

f(a:b)=f b

f"a" runs recursively through the string "a" by dropping the first char and eventually fails at its end with a Non-exhaustive patterns in function f exception, because f is only defined for non-empty strings.


Pyth, 3 bytes


Try it online.

W1 is just while 1: in Python. The loop body prints a line read from STDIN, which crashes for the second iteration when the code is run with empty input.

If loops using # (loop-until-error) are banned (I assume so), I think this is the shortest it can get.


C#, 71 38 bytes

Since you provided an example in C# here another version golfed

And thanks to pinkfloydx33

void c(){checked{for(uint i=1;;i--);}}

Shorter than Parse.ToString() and even than Parse($"{c--}") I mentally dumped checked for it being too long of a keyword. Tough it certainly is shorter than Parse(c.ToString())

Original answer

class p{static void Main(){for(int c=0;;c--)uint.Parse(c.ToString());}}

This will start c=0 then decrement it, when c=-1 the uint.Parse will cause an:

Unhandled Exception: System.OverflowException: Value was either too large or too small for a UInt32.

Ungolfed version and verifying that loop runs at least once

class p {
    static void Main() {
        for(int c=0;;c--) {
  • \$\begingroup\$ for(int c=0;;)uint.Parse($"{c--}"); \$\endgroup\$ Commented Dec 24, 2016 at 12:24
  • 1
    \$\begingroup\$ checked{for(uint c=1;;)c--;} \$\endgroup\$ Commented Dec 24, 2016 at 12:38
  • \$\begingroup\$ Ok, wow! Didn't know about the '$' shorthand! \$\endgroup\$
    – MrPaulch
    Commented Dec 24, 2016 at 12:58
  • \$\begingroup\$ Using int instead of uint works for -1 byte. \$\endgroup\$
    – wastl
    Commented Feb 17, 2021 at 1:20

CJam, 4 bytes


P` generates the string 3.141592653589793. :~ evaluates each character. 3 is valid code in CJam which simply returns 3. In the next iteration, . causes an error because it requires a digit or an operator following it.


JavaScript, 9 bytes


This runs once, then throws ReferenceError: i is not defined which stops the loop.

// With a console.log(1) to see that it runs once.

Taking the following as an example, is the <increment> the end of the first cycle or the beginning of the second cycle ?

2:  <statement>;

1/ I see it

After going from lines 0 to line 3 then going back to line 0, it feels like a full cycle has been completed.
That would make the <increment> the beginning of the second cycle.
- First cycle : <init> -> <test> -> <statement>
- Second cycle : <increment> -> <test> -> <statement>

2/ While equivalent

3:  <statement>;
4:  <increment>;

In this equivalent while the <increment> is the end of the first cycle and it feels like it's the same with the for.
That would make the <increment> the end of the first cycle.
- First cycle : <test> -> <statement> -> <increment>
- Second cycle : <test> -> <statement> -> <increment>

3/ A statement is encountered twice

A full cycle is completed when a statement is encountered twice.
The first statement encountered twice is <test>.
That would make the <increment> the end of the first cycle.
- First cycle : <test> -> <statement> -> <increment>
- Second cycle : <test> -> <statement> -> <increment>

4/ It's a setup

The <init> is just setting up whatever is needed for the first cycle.
The <increment> is just setting up whatever is needed for the second cycle.
That would make the <increment> the beginning of the second cycle.
- First cycle : <init as a setup> -> <test> -> <statement>
- Second cycle : <increment as a setup> -> <test> -> <statement>

The ECMAScript® 2016 Language Specification

Runtime of for(<init>;<test>;<increment>)<statement>;

Let varDcl be the result of evaluating <init>.
Return ? ForBodyEvaluation(<test>, <increment>, <statement>, « », labelSet).

There are three forms, so I took the shortest one here, there's no difference:
- Whatever the <init> it isn't part of the first iteration.
- What's relevant is in ForBodyEvaluation.

Details of ForBodyEvaluation(<test>, <increment>, <statement>, « », labelSet)

0 Let V be undefined.
1 Perform ? CreatePerIterationEnvironment(perIterationBindings).
2 Repeat
3  If is not [empty], then
4   Let testRef be the result of evaluating <test>.
5   Let testValue be ? GetValue(testRef).
6   If ToBoolean(testValue) is false, return NormalCompletion(V).
7  Let result be the result of evaluating <statement>.
8  If LoopContinues(result, labelSet) is false, return Completion(UpdateEmpty(result, V)).
9  If result.[[Value]] is not empty, let V be result.[[Value]].
10  Perform ? CreatePerIterationEnvironment(perIterationBindings).
11  If is not [empty], then
12   Let incRef be the result of evaluating <increment>.
13   Perform ? GetValue(incRef).

6/ I see it

A full cycle a full run of the repeat part.
That would make the <increment> the end of the first cycle.
- First cycle : <test> -> <statement> -> <increment> / In other words from line 3 to line 13
- Second cycle : <test> -> <statement> -> <increment> / In other words from line 3 to line 13

7/ A cycle is an iteration

A cycle begin with CreatePerIterationEnvironment.
So when CreatePerIterationEnvironment is encountered a new cycle begins, thus ending the previous one.
That would make the <increment> the beginning of the second cycle.
- First cycle : <test> -> <statement> / In other words from line 1 to line 9
- Second cycle : <increment> -> <test> -> <statement> / In other words from line 10 looping until line 9

Is the <increment> the end of the first cycle or the beginning of the second cycle?

The right explanation is either 6 or 7.

  • 8
    \$\begingroup\$ I think I'm more inclined to ascribe the increment to the end of the first iteration, rather than to the beginning of second iteration or to neither iteration. I suppose this is an ambiguity of the question. \$\endgroup\$
    – user16488
    Commented Dec 23, 2016 at 22:46
  • 1
    \$\begingroup\$ Since for(a;b;c)d; is roughly equivalent to a;while(b){d;c;}, I'm inclined to say that the error is still thrown in the first iteration (before the loop condition is checked a second time). \$\endgroup\$ Commented Dec 23, 2016 at 22:54
  • \$\begingroup\$ @Hurkyl The first iteration begin with the initialisation, so I think that the increment should be the begining of the second iteration. \$\endgroup\$
    – Hedi
    Commented Dec 23, 2016 at 22:57
  • 4
    \$\begingroup\$ If you read the spec, you can see that the increment operation is the last part of the iteration and as such, still belongs in the first iteration. \$\endgroup\$
    – Etheryte
    Commented Dec 26, 2016 at 14:19
  • 3
    \$\begingroup\$ @Hedi I don't see how that is relevant at all. The increment operation is very clearly a part of the first run of the loop. To rephrase, when the increment operation is called, the loop has not finished a single full run. \$\endgroup\$
    – Etheryte
    Commented Dec 26, 2016 at 19:32

x86 assembly (AT&T syntax), 40 bytes

mov $1,%eax
div %eax
dec %eax
je A

Declares a function f which divides 1 by 1 on its first iteration then attempts to divide 0 by 0 and errors.

  • \$\begingroup\$ You can save 4 bytes by switching to Intel syntax :) \$\endgroup\$
    – mriklojn
    Commented Dec 24, 2016 at 1:08
  • 6
    \$\begingroup\$ We usually score assembly by the size of the generated byte code, not the human-readable instructions. \$\endgroup\$
    – Dennis
    Commented Dec 24, 2016 at 1:35
  • \$\begingroup\$ @Dennis assmebled assembly is machine language. but yeah this could be claimed much shorter in machine language form. \$\endgroup\$
    – Jasen
    Commented Dec 25, 2016 at 2:51
  • 1
    \$\begingroup\$ Get rid of the f-label and the mov. Swap the dec and div, and you can get rid of even more. \$\endgroup\$
    – Clearer
    Commented Jan 27, 2017 at 20:39

Ruby, 14 Bytes


Exits due to ZeroDivisionError: divided by 0

$. The current input line number of the last file that was read

Ruby Docs


><>, 3 bytes


Try it here!


!    skip next instruction
 ]   close stack (crash)
  !  skip next instruction (jumping to close stack)

Batch, 22 20 bytes

set i=%i%1
goto a


This is an infinite loop that appends a 1 onto an initially empty string. Eventually this will pass the maximum string length of 8192 and crash. On my machine, this takes about 30 seconds.

  • \$\begingroup\$ Nice! You can save 2 bytes by using Unix line endings. \$\endgroup\$
    – briantist
    Commented Dec 27, 2016 at 0:49
  • \$\begingroup\$ You can use %0 which is the filename instead of the label and goto. \$\endgroup\$ Commented Jan 1, 2017 at 18:14
  • \$\begingroup\$ I wasn't sure if that broke the tail recursion rule. \$\endgroup\$ Commented Jan 1, 2017 at 18:15

INTERCAL, 12 bytes


Try it online!

NEXT is INTERCAL-72's main control flow command. (Later revisions introduced COME FROM, which became more famous, but it wasn't in the original version of the language; and all finished INTERCAL implementations I'm aware of support NEXT for backwards compatibility, with all but one enabling support for it by default. So I don't feel the need to name INTERCAL-72 specifically in the title.)

When using NEXT to form a loop, you're supposed to use RESUME or FORGET in order to free up the space that it uses to remember where the program has been; RESUME retroactively makes the NEXT into something akin to a function call (although you can return from functions other than the one you're in) whereas FORGET makes it into something more similar to a GOTO statement. If you don't do either (and this program doesn't), the program will crash after 80 iterations (this behaviour is actually specified in the INTERCAL specification).

It's somewhat ambiguous whether this counts as unbounded recursion (disallowed in the question); you can certainly use this sort of NEXT to implement a function call, in which case it would effectively be a recursive function, but there's not enough information here to determine whether we're doing a function call or not. At least, I'm posting this anyway because it doesn't unambiguously violate the rules, and an INTERCAL implementation that optimized out the "tail call" would not only violate the specification, but also cause most existing programs to break, because returning from the "wrong function" is the main way to do the equivalent of an IF statement.

Here's the resulting error message, as generated by C-INTERCAL:


(Note that the second line is indented with a tab, and the third with eight spaces. This looks correct in a terminal, or in pretty much any program that has tab stops at multiples of 8. However, Markdown has tab stops at multiples of four, violating the assumptions that most older programs make about tabs, so the error message is a little malformatted here.)

  • \$\begingroup\$ Does the error really say CORRECT SOURCE AND RESUBNIT? As in a typo in the original C-INTERCAL error message? \$\endgroup\$
    – Andrakis
    Commented Dec 25, 2016 at 5:37
  • 2
    \$\begingroup\$ @Andrakis: Yes, it does. That typo's been carefully preserved for years. \$\endgroup\$
    – user62131
    Commented Dec 25, 2016 at 12:35

Rust, 23 bytes

||for i in 0..{[()][i]}

Try it online!

Similar to TehPers's answer, but using a unit type array instead of a string gets rid of the &, .. and ;

  • \$\begingroup\$ Same length, but you could replace the array's contents with any single digit and add a semicolon: ||for i in 0..{[0][i];}. I like your approach a lot more though because it's creative :) \$\endgroup\$
    – TehPers
    Commented Oct 15, 2020 at 17:32

Python 3, 29 bytes

def x(n):del i;x(i)

Really simple. On the second call to x, i isn't there, and Python complains about it.


Labyrinth, 3 bytes


Try it online!

Like most 2D languages, Labyrinth doesn't have any explicit looping constructs. Instead, any code that is laid out such that it is executed multiple times in a row is a loop in these languages. For the case of Labyrinth, a simple linear program acts as a loop, because the instruction pointer will bounce back and forth on it. If the program is abc (for some commands a, b and c), then the actual execution will be abcbabcbabcb... so it runs abcb in an infinite loop.

As for why this particular program crashes on the second iteration of this loop, here is what the individual commands do. Note that Labyrinth's stack contains an implicit infinite amount of zeros at the bottom:

#   Push stack depth.   [... 0]
(   Decrement.          [... -1]
/   Divide.             [... 0]
(   Decrement.          [... -1]
#   Push stack depth.   [... -1 1]
(   Decrement.          [... -1 0]
/   Divide.             Crashes with division-by-zero error.

Bash, 11 (Borderline non-competing)

exec $0 1$@

This script recursively execs itself, appending 1 to the args passed on each iteration. I think this counts as TCO because exec reuses the process space but doesn't eat up stack. It is borderline non-competing because it took about 10 minutes before being killed on my machine - YMMV.

  • 1
    \$\begingroup\$ exec $0 1$@$@ terminates much faster but is two characters longer. \$\endgroup\$
    – Jasen
    Commented Dec 25, 2016 at 2:54

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