Shortest auto-destructive loop [closed]

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.

Rules:

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;
Console.WriteLine(n[i]);
}
}
}

Output:

0
1
2
3
4
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


Leaderboard:

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

• 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) Dec 23 '16 at 22:06
• @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." Dec 23 '16 at 22:13
• @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. Dec 24 '16 at 1:20
• 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. Dec 25 '16 at 11:43
• 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. Jun 16 '21 at 3:22

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)

i=1
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.

• The 17 bytes solution also works if you replace while i with while 1 because it tries to delete i again; Dec 24 '16 at 17:56
• @user6245072 yep, both snippets can be trivially modified for lots of working solutions Dec 24 '16 at 18:11
• You can use your del trick with a built-in to shave off a few more: while 1:del id.
– DSM
Dec 24 '16 at 21:02
• @DSM: del id doesn't work. You can't delete builtins that way. Dec 28 '16 at 3:34

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

2:t"x


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

• Works offline as well. No input means you can assume empty input. Dec 23 '16 at 22:29
• @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? Dec 23 '16 at 22:32
• 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. Dec 23 '16 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:

'0'
'”0'
'””,”0'
'””,””,”,,””,”0'
'””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,”0'
'””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,”,,”,,””,”,,”,,””,””,”,,””,””,”,,””,”,,”,,””,””,”,,””,”0'


After that, it gets real ugly, real fast.

• What is jelly's memory limits? Dec 24 '16 at 0:09
• 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. Dec 24 '16 at 0:40
• So every 2 years, we'll be able to execute another iteration Dec 24 '16 at 0:43
• So will fail condition #5 on slow machine with lots of RAM? Dec 27 '16 at 22:18
• @MadPhysicist That is correct. This is a inherent problem with time limits though. Compliance depends very much on which machine the program is run. Dec 27 '16 at 22:22

V, 2 bytes

òl


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)

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

JavaScript (ES6), 13 bytes

f=_=>f(_?a:1)


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:

for(i=0;;)i=i.a


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

H;G;D

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  • Hi, how about s:a\?:&a:g? It is 1 byte less and doubles the pattern size per iteration as well. Feb 3 '17 at 15:48 • @seshoumara I don't think that'll match anything when the pattern space is empty, so it'll never make the first replacement. Feb 3 '17 at 15:54 • @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. Feb 3 '17 at 16:25 • 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. Feb 3 '17 at 16:33 • @seshoumara I thought it would still give it an empty string. That seems to work then. Thanks! Feb 3 '17 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. Verification $ 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, 222120 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 [...][...]. while($x.=pi)$x();  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. for($x=pi;;)$x=$x();


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! • 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. Dec 27 '16 at 14:56
• I thought of a different approach Dec 27 '16 at 15:22
• @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. Dec 28 '16 at 9:52
• You could use pi instead of abs. That doesn´t even yield a warning before it throws the fatal. Jan 9 '17 at 16:39
• @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! Jan 9 '17 at 18:36

C, 21 bytes

i;f(){for(;1/!i++;);}


Here i is guaranteed to start off as 0.

It can be confirmed that this runs once like so:

i;f(){for(;1/!i++;)puts("hi");}
main(){f();}


Which, on my machine, results in:

llama@llama:...code/c/ppcg104323loop$./a.out hi zsh: floating point exception (core dumped) ./a.out  The shortest recursive solution I can find is 22 bytes: f(i){f(i-puts(""-i));}  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
main(){f();}
f(i){f(i-puts(""-i));}
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:

main(i){for(;1/i--;);}


which is equivalent to the function of the same length:

f(i){for(i=1;1/i--;);}

• 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). Dec 24 '16 at 0:40
• Or, the argument register still has the value that was there from main getting called. Dec 24 '16 at 0:47
• @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!
– Doorknob
Dec 24 '16 at 1:02
• 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. Dec 24 '16 at 1:08
• Yep, tio Dec 24 '16 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.

repeat(ls(T<-T-1))


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.

• That doesn't sound like the recursion is done with tail call optimization, if there is a recursion limit.
– user45941
Dec 23 '16 at 23:15
• @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. Dec 23 '16 at 23:22

FALSE, 8 bytes

I really like this language.

1[$][.]#  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: 1[$][..]#

• You should also try DUP, which is basically a superset of FALSE. That's what I used to make RETURN. Dec 24 '16 at 3:04
• @MamaFunRoll oh yeah, I forgot that you made RETURN! I gotta try that one. :D Dec 24 '16 at 3:12
• @MamaFunRoll I love DUP, I just wrote a DUP interpreter and I’m playing around with it.
– M L
Dec 27 '16 at 18:20
• @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. – M L Dec 27 '16 at 18:36 • 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. – M L Dec 27 '16 at 19:00 QBasic, 17 bytes This code is very weird. DO i=11+a(i) LOOP  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: DO ?a(i) i=i+1 LOOP  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. • QBasic and arrays, where does the fun stop! Dec 24 '16 at 9:59 • Since the error doesn't have to be on the second loop, couldn't you do i=1+a(i)? Dec 24 '16 at 15:40 • @Quelklef No, you'd have to do i=i+1+a(i). Otherwise the index never gets above 1, which isn't an error. Dec 24 '16 at 19:31 • @DLosc Oh, you're right. Dec 25 '16 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'." • Both of those are awesome! You probably know this, but j(2) would normally give a 2-by-2 matrix with 0+1i Apr 10 '17 at 10:18 • Thanks! That's true in Octave but not in MATLAB I think – hwm Apr 11 '17 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

1{}g


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"


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

W1w


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--) { System.Console.Write(c); uint.Parse(c.ToString()); } } }  • for(int c=0;;)uint.Parse($"{c--}"); Dec 24 '16 at 12:24
• checked{for(uint c=1;;)c--;} Dec 24 '16 at 12:38
• Ok, wow! Didn't know about the '$' shorthand! Dec 24 '16 at 12:58 • Using int instead of uint works for -1 byte. Feb 17 '21 at 1:20 CJam, 4 bytes P:~  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 for(;;i);  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. for(;;i)console.log(1); Taking the following as an example, is the <increment> the end of the first cycle or the beginning of the second cycle ? 0:for(<init>;<test>;<increment>) 1:{ 2: <statement>; 3:}  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 0:<init>; 1:while(<test>) 2:{ 3: <statement>; 4: <increment>; 5:}  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>. ReturnIfAbrupt(varDcl). 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. • 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. – user16488 Dec 23 '16 at 22:46 • 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). Dec 23 '16 at 22:54 • @Hurkyl The first iteration begin with the initialisation, so I think that the increment should be the begining of the second iteration. – Hedi Dec 23 '16 at 22:57 • 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. Dec 26 '16 at 14:19 • @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. Dec 26 '16 at 19:32 x86 assembly (AT&T syntax), 40 bytes f: mov$1,%eax
A:
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.

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

Ruby, 14 Bytes

loop{$./=~$.}


Exits due to ZeroDivisionError: divided by 0