# Shortest auto-destructive loop

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


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) – ETHproductions 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." – Mario Dec 23 '16 at 22:13
• In for(a;b;c)d;, after wich statement ends the first cycle ? Is it valid to break on the first evalution of c statement ? – Hedi Dec 23 '16 at 23:54
• @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. – ETHproductions 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. – BrainStone Dec 25 '16 at 11:43

# 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. – Dennis 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? – Luis Mendo 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. – Dennis Dec 23 '16 at 22:34

# 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; – user6245072 Dec 24 '16 at 17:56
• @user6245072 yep, both snippets can be trivially modified for lots of working solutions – FlipTack 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. – user2357112 Dec 28 '16 at 3: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? – tuskiomi 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. – Dennis Dec 24 '16 at 0:40
• So every 2 years, we'll be able to execute another iteration – tuskiomi Dec 24 '16 at 0:43
• So will fail condition #5 on slow machine with lots of RAM? – Mad Physicist 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. – Dennis 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"? – Conor O'Brien Dec 24 '16 at 3:50
• @ConorO'Brien yep. There's actually some good historical reasons for this. – DJMcMayhem Dec 24 '16 at 3:53
• The challenge requires answers to crash on the second iteration or later, not on the first iteration. – Martin Ender 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.

# 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.

# 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.

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. – aross Dec 27 '16 at 14:56 • I thought of a different approach – aross 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. – Ismael Miguel 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. – Titus 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! – Ismael Miguel Jan 9 '17 at 18:36 # 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. – seshoumara 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. – Riley 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. – Riley 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. – seshoumara Feb 3 '17 at 16:33
• @seshoumara I thought it would still give it an empty string. That seems to work then. Thanks! – Riley Feb 3 '17 at 16:39

## 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. – Mego 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. – Billywob Dec 23 '16 at 23:22

# 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.

# 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. – Mama Fun Roll Dec 24 '16 at 3:04
• @MamaFunRoll oh yeah, I forgot that you made RETURN! I gotta try that one. :D – Conor O'Brien 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 ## 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). – Riley Dec 24 '16 at 0:40 • Or, the argument register still has the value that was there from main getting called. – Riley 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. – Riley Dec 24 '16 at 1:08 • Yep, tio – Riley Dec 24 '16 at 1:11 # 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 – Stewie Griffin Apr 10 '17 at 10:18 • Thanks! That's true in Octave but not in MATLAB I think – MattWH 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.

# 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! – steenbergh 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)? – Quelklef 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. – DLosc Dec 24 '16 at 19:31
• @DLosc Oh, you're right. – Quelklef Dec 25 '16 at 21:25

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.

# 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--}"); – pinkfloydx33 Dec 24 '16 at 12:24
• checked{for(uint c=1;;)c--;} – pinkfloydx33 Dec 24 '16 at 12:38
• Ok, wow! Didn't know about the '$' shorthand! – MrPaulch Dec 24 '16 at 12:58 ## 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. ### 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 :) – mriklojn Dec 24 '16 at 1:08
• We usually score assembly by the size of the generated byte code, not the human-readable instructions. – Dennis Dec 24 '16 at 1:35
• @Dennis assmebled assembly is machine language. but yeah this could be claimed much shorter in machine language form. – Jasen 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. – Clearer Jan 27 '17 at 20:39

# 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.

## Ruby, 14 Bytes

loop{$./=~$.}


Exits due to ZeroDivisionError: divided by 0

# cmd, 34 bytes

for /l %i in (0,1,10) do color %i0


This will cycle %i from 0 to 10. The (ancient) color command will happily accept any argument that has 2 (hexa-)decimal digits. With the argument 100 it will fail, printing the the help message and setting ERRORLEVEL to 1.

Proof of the loop running at least once: The color of your shell will be different!