117

Back in my C/C++ days, coding an "infinite loop" as

while (true)

felt more natural and seemed more obvious to me as opposed to

for (;;)

An encounter with PC-lint in the late 1980's and subsequent best practices discussions broke me of this habit. I have since coded the loops using the for control statement. Today, for the first time in a long while, and perhaps my first need for an infinite loop as a C# developer, I am facing the same situation. Is one of them correct and the other not?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bob Kaufman
  • 12,864
  • 16
  • 78
  • 107
  • 6
    Four identical answers in under two minutes. Not bad. – Jon B Sep 09 '09 at 18:09
  • I swear this is an exact duplicate, but SO's search engine ignores "for" and "while" as common words, so I can't find the original. ;-) – Ben Blank Sep 09 '09 at 18:10
  • @Ben - I agree there has to be an original to this, however I spent 20 minutes searching for it to no avail! – Bob Kaufman Sep 09 '09 at 18:11
  • I agree with all of you that "while ( true )" is easier to read and more obvious. I'm interested in best practices and established standards. – Bob Kaufman Sep 09 '09 at 18:13
  • @Bob: As I said in my answer, this has always been the convention that I have seen people adopt in C#. I have seen empty for loops in other languages, but in C# it always seems to be while(true). – Adam Robinson Sep 09 '09 at 18:15
  • @Adam - the evidence weighs overwhelmingly in your favor! At this point, I tend to go into a long-winded diversion using the word "ain't" as an example of how usage infers acceptance. Suffice to say that while ( true ) appears to be the accepted answer. – Bob Kaufman Sep 09 '09 at 18:18
  • @Bob: while(true) is the best practice for creating infinite loops if there ever was a practice that required such... The for(;;) is difficult to read and leads to way too much confusion. while(1) is not something that will work in C#. – RSolberg Sep 09 '09 at 18:21
  • 6
    You could avoid the whole religious argument by unrolling your infinite loop. Shouldn't take long... – Stephen Darlington Sep 09 '09 at 18:23
  • @RSolberg - good point. I'm editing things accordingly. – Bob Kaufman Sep 09 '09 at 18:32
  • ... Allen beat me to it. Thanks! :) – Bob Kaufman Sep 09 '09 at 18:33
  • 7
    Just out of curiosity: why is for(;;) better in C/C++? – Vilx- Sep 09 '09 at 18:47
  • 6
    @Vilx as I recall it, old compilers used to write more efficient code with for(;;) than while(1). I'm sure that any decent modern compiler will output pretty much identical code. – Stephen Darlington Sep 09 '09 at 21:55
  • *Spaces* excessive usage. I'd use like this: `while (true)` and `for (; ; )` – serhio Jul 04 '10 at 14:55
  • 4
    Building on Stephen and Serhio's comments: 1. `while(true)` requires a condition. `for(;;)` is therefore a better representation for infinite loops which repeat unconditionally. 2. Old unoptimizing compilers may have actually evaluated the `(true)` as it looped. 3. C is a minimalist language from the days of teletypes, 300 baud terminals, and 1-char variable names. In an environment where every key stroke counts, `for(;;)` is quite a bit shorter than `while(true)`. – Richard Dingwall Mar 11 '11 at 11:26
  • 2
    As of C/C++, some compiles can produce a "conditional expression is constant" warning in case of while(true). – Alex Che Sep 16 '13 at 08:40
  • 1
    "Which approach is faster and which is more memory efficient" is probably a better way to phrase the question – Phil Feb 11 '14 at 23:16

20 Answers20

344

The C# compiler will transform both

for(;;)
{
    // ...
}

and

while (true)
{
    // ...
}

into

{
    :label
    // ...
    goto label;
}

The CIL for both is the same. Most people find while(true) to be easier to read and understand. for(;;) is rather cryptic.

Source:

I messed a little more with .NET Reflector, and I compiled both loops with the "Optimize Code" on in Visual Studio.

Both loops compile into (with .NET Reflector):

Label_0000:
    goto Label_0000;

Raptors should attack soon.

Community
  • 1
  • 1
Pierre-Alain Vigeant
  • 22,635
  • 8
  • 65
  • 101
133
while(true)
{

}

Is always what I've used and what I've seen others use for a loop that has to be broken manually.

Adam Robinson
  • 182,639
  • 35
  • 285
  • 343
61

I think that this may be easier to read and is definitely the standard for use in C#:

while(true)
{
   //Do My Loop Stuff
}
RSolberg
  • 26,821
  • 23
  • 116
  • 160
54

Gasp, use:

while (!false)
{

}

OR as jsight pointed out, you may want to be doubly sure:

while (!false && true)
{
}

Before people yell at me, it's all the same CIL code, I checked :)

Community
  • 1
  • 1
Allen Rice
  • 19,068
  • 14
  • 83
  • 115
37

To rehash a couple of old jokes:

  1. Don't use "for (;;) {}" — it makes the statement cry.
  2. Unless, of course, you "#define EVER ;;".
Ben Blank
  • 54,908
  • 28
  • 127
  • 156
28

If you want to go old school, goto is still supported in C#:

STARTOVER:  
    //Do something
    goto STARTOVER;

For a truly infinite loop, this is the go-to command. =)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JohnFx
  • 34,542
  • 18
  • 104
  • 162
  • 9
    http://xkcd.com/292/ – Callum Rogers Sep 09 '09 at 18:40
  • 6
    I upvoted this from a negative rating back to zero, but only because of its humor value. Hey, all loops get compiled into JMP assembler opcodes anyway, right? – David R Tribble Sep 09 '09 at 18:44
  • @Loadmaster: Thanks, I was just throwing it out there as another option, not necessarily endorsing it. – JohnFx Sep 09 '09 at 19:09
  • -1 don't use goto in C#, nor in VB.NET: bad practice in modern language. – serhio Jul 04 '10 at 14:48
  • 2
    @serhio: Even more so is avoiding language constructs out of hand because you read something somewhere. No language element by itself is bad, it can only be used in bad ways. – JohnFx Jul 04 '10 at 15:51
  • @JohnFx: Yes, John, don't use goto, because you probably will use it in a bad way. take a look http://david.tribble.com/text/goto.html – serhio Jul 04 '10 at 16:03
  • 2
    @serhio: I have seen abominations against nature using just about every keyword possible. It isn't the language element, it is the programmer. In any case, as noted in my previous comment, I wasn't endorsing it. I was just including it for completeness and a tingle of humor. – JohnFx Jul 05 '10 at 15:28
  • @serhio: Hey, thanks for referencing my *goto* article! – David R Tribble Jul 05 '10 at 19:42
  • @Loadmaster: Are you David?... a, ok, I see :) good work. However, you convinced not everbody. – serhio Jul 05 '10 at 20:45
  • @serhio: Yes, because most programmers are still taught the knee-jerk reaction that all gotos are evil, without being taught any of the history behind it all. – David R Tribble Jul 08 '10 at 20:08
22

I think while (true) is a bit more readable.

Thom Smith
  • 13,916
  • 6
  • 45
  • 91
Marplesoft
  • 6,030
  • 4
  • 38
  • 46
12

In those situations where I needed a true infinite loop, I've always used

while(true) {...}

It seems to express intent better than an empty for statement.

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
10

Personally, I have always preferred for(;;) precisely because it has no condition (as opposed to while (true) which has an always-true one). However, this is really a very minor style point, which I don't feel is worth arguing about either way. I've yet to see a C# style guideline that mandated or forbade either approach.

Pavel Minaev
  • 99,783
  • 25
  • 219
  • 289
  • don't worth in .NET, when compiler transforms your (bad readable) *for* without condition in a *while* with condition. – serhio Jul 04 '10 at 14:53
  • 4
    @serhio: please explain what you mean by "compiler transforms ... in a `while`". As far as programmer is concerned, the compiler transforms high-level code into IL. There are no `while` (or `for`) loops in IL, only labels and gotos. – Pavel Minaev Jul 04 '10 at 19:26
  • 1
    see Pierre-Alain Vigeant 's answer. – serhio Jul 05 '10 at 08:42
  • 4
    His answer can be better rephrased as simply "the compiler generates identical IL for both" (you don't really know if and when it transforms anything on AST level, and it's an implementation detail in any case). In any case, this doesn't explain why it's "not worth it in .NET". The same is also true of C++, Java... – Pavel Minaev Jul 05 '10 at 14:54
6

I personally prefer the for (;;) idiom (coming from a C/C++ point of view). While I agree that the while (true) is more readable in a sense (and it's what I used way back when even in C/C++), I've turned to using the for idiom because:

  • it stands out

I think the fact that a loop doesn't terminate (in a normal fashion) is worth 'calling out', and I think that the for (;;) does this a bit more.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
  • finally, using that we will wait a little more that the programs compile(compile transformation from for=>while) – serhio Jul 04 '10 at 14:50
  • 4
    @serhio: Not really. It doesn't *transform* it from `for` to `while`. For both `for (;;){}` and `while (true){}`, it generates new `while(true){}` code. See [this answer](http://stackoverflow.com/a/1401208/732016). – wchargin Aug 25 '12 at 21:23
  • I agree because I feel like `for (;;)` declares intent more clearly. e.g., although the _action_ is clear, a `while (true)` statement looks like someone forgot to pass a variable. – Joshua Barker Apr 27 '23 at 20:15
6

The original K&R book for C, from which C# can trace its ancestry, recommended

for (;;) ...

for infinite loops. It's unambiguous, easy to read, and has a long and noble history behind it.

Addendum (Feb 2017)

Of course, if you think that this looping form (or any other form) is too cryptic, you can always just add a comment.

// Infinite loop
for (;;)
    ...

Or:

for (;;)    // Loop forever
    ...
David R Tribble
  • 11,918
  • 5
  • 42
  • 52
5

It should be while(true) not while(1), so while(1) is incorrect in C#, yes ;)

Thom Smith
  • 13,916
  • 6
  • 45
  • 91
JRL
  • 76,767
  • 18
  • 98
  • 146
3

Even I also say the below one is better :)

while(true)
{

}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
anishMarokey
  • 11,279
  • 2
  • 34
  • 47
2

In terms of code readability while(true) in whatever language I feel makes more sense. In terms of how the computer sees it there really shouldn't be any difference in today's society of very efficient compilers and interpreters.

If there is any performance difference to be had I'm sure the translation to MSIL will optimise away. You could check that if you really wanted to.

Thom Smith
  • 13,916
  • 6
  • 45
  • 91
Chris
  • 2,447
  • 1
  • 21
  • 27
2

Alternatively one could say having an infinite loop is normally bad practice anyway, since it needs an exit condition unless the app really runs forever. However, if this is for a cruise missile I will accept an explicit exit condition might not be required.

Though I do like this one:

for (float f = 16777216f; f < 16777217f; f++) { } 
Chris Chilvers
  • 6,429
  • 3
  • 32
  • 53
  • 3
    -1: not everyone will understand your "infinite loop" reading the code, perhaps somebody could think this is a bug and try to "fix" it... – serhio Jul 05 '10 at 09:13
  • 1
    In C# `f < 16777217f` is always `false`... so this never loops. – NetMage Jul 24 '19 at 20:17
2

Both of them have the same function, but people generally prefer while(true). It feels easy to read and understand...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
abhinav
  • 151
  • 4
  • 11
1

The only reason I'd say for(;;) is due the CodeDom limitations (while loops can't be declared using CodeDom and for loops are seen as the more general form as an iteration loop).

This is a pretty loose reason to choose this other than the fact that the for loop implementation can be used both for normal code and CodeDom generated code. That is, it can be more standard.

As a note, you can use code snippets to create a while loop, but the whole loop would need to be a snippet...

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mark Synowiec
  • 5,385
  • 1
  • 22
  • 18
1

I prefer slightly more "literate" code. I'm much more likely to do something like this in practice:

bool shouldContinue = true;
while (shouldContinue)
{
    // ...

    shouldContinue = CheckSomething();
}
bobbymcr
  • 23,769
  • 3
  • 56
  • 67
  • 2
    Ugh. Actutally, that's a `do ... while()` loop in disguise. It just took me a few seconds to see that. Had you written a `do ... while()` loop, it would have been clear immediately. -1 – sbi Sep 09 '09 at 19:08
  • why waste time and resources declaring a variable when you can use while(true)? It doesn't make sense in my opinion – waqasahmed Sep 09 '09 at 22:26
  • I find it more readable, especially if you can attach a specific meaningful flag, e.g. "while (!this.canceled)" to indicate that cancellation is the only way to stop the loop, "while (!processExited)" to indicate the loop should run until an external process goes away, etc. There are lots of things that arguably "waste resources" that are absolutely the right thing to do in the name of ease of maintainability or readability. "while (true)" isn't all that bad, but in my experience there's usually a better way. – bobbymcr Sep 09 '09 at 22:54
  • 1
    +1. In most cases, a true infinite loop isn't what actually happens, and you do have some condition where you'd wish to stop (e.g. when the printer is on fire). – Lie Ryan Sep 27 '10 at 21:56
  • 4
    … in which case you should use `break`. – Ry- Oct 12 '13 at 19:33
1

If you're code-golfing, I would suggest for(;;). Beyond that, while(true) has the same meaning and seems more intuitive. At any rate, most coders will likely understand both variations, so it doesn't really matter. Use what's most comfortable.

sobellian
  • 11
  • 1
-1

Any expression that always returns true should be OK for while loop.

Example:

1==1 //Just an example for the text stated before 
true
George
  • 1,466
  • 3
  • 12
  • 30
  • 2
    Why would you ever bother forcing it to do a comparison like 1=1 when true works just as well? Using a calculated expression feels about as silly as defining a constant like NUMBER_OF_ARMS = 598-3596; – JohnFx Sep 09 '09 at 18:35
  • Its an example for the answer stated before the code :) – George Sep 09 '09 at 18:39