views:

2041

answers:

22

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?

+14  A: 

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

Marplesoft
+33  A: 

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
Any seasoned developer would understand `while(1){/**/}`. Those extra keystrokes don't come free you know! :)
voyager
@voyager: 1 is not a substitute for 'true' in C#.
Adam Robinson
@voyager: I code for the unseasoned...
RSolberg
Note that while(1) is invalid C#: Constant 1 cannot be converted to bool
Vinko Vrsalovic
`while(1)` isn't valid in C#, since `1` is not a `bool`.
Pavel Minaev
+1, returning the favor!
Adam Robinson
+50  A: 
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
+1: we answered within seconds... I'll share some "rep" to get you to 10K!
RSolberg
+1 and accepted: Usage infers acceptance!
Bob Kaufman
Unfortunately, yes!
Adam Robinson
We should get to share the answer on this or something...
RSolberg
@RSolberg - it was a toss-up between the two similar responses offered within seconds of one another. Adam's follow-up comment led me to accepting an answer based on usage rather than convention.
Bob Kaufman
while and for can both be broken manually
Allen
Congratulation on the 10k reputation
Pierre-Alain Vigeant
@Adam: Congrats!
RSolberg
+8  A: 

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
+3  A: 

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

JRL
A: 

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.

Chris
A: 

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

Mark Synowiec
+9  A: 

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
Or `#define ever (;;)` which I think is more readable. `for ever {}`
Chris Lutz
I didnt think you could do a #define ever (;;) in C#, though, the joke is funny :)
Allen
Ah. I program C on OS X. I didn't know the C# preprocessor was so castrated. I'm not even sure how I started reading this question, I have C# as an ignored tag...
Chris Lutz
The C# preprocessor is not really a preprocessor, at least not in terms of what C, C++, PL/1, and even macro assemblers provide. It only allows you to enable or disable blocks of code by defining/undefining preprocessor symbols.
Loadmaster
Or even better: `#define forever while(true)` ;)
Roberto Bonvallet
the question is about C#, not C++, we can't #define ;;
serhio
+120  A: 

The C# compiler will transform

for(; ; )
{
}

into

while (true)
{
}

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

Edit

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

Both loop compile into (with Reflector)

Label_0000:
    goto Label_0000;

Raptors should attack soon.

Pierre-Alain Vigeant
yup, just double checked, its all the same IL code, this should be the accepted answer IMO :)
Allen
shame you weren't first. this is complete, researched, and correct.
dnord
+1 for the xkcd reference
Ikke
Best answer in the thread for sure.
KingNestor
+ 1: for taking the time to prove it all out...
RSolberg
To be pedantic, the compiler does *not* transform one statement form into the other; rather, it generates identical code for both statements. That code is identical to a `goto` statement, btw, which is no surprise.
Loadmaster
and then the goto is translated to a jmp instruction..
Marco M.
so obviously `goto LOOP` is the correct C# infinite loop :)
Dustin Getz
@Dustin: Premature optimization ... you know the rest :P
Pierre-Alain Vigeant
While very interesting, technically it is not an answer to the question. If for(;;) was a fraction faster, would we recommend using it?
Henk Holterman
The question wasn't about speed either. it was about if it is correct or not. I said that `while(true)` may be easier to read and to understand by most people.
Pierre-Alain Vigeant
+1 to put you at 100. Congrats!
Adam Robinson
Haha thank you. I now have won two gold medals with this answer.
Pierre-Alain Vigeant
+16  A: 

Gasp, what about

while (!false)
{

}

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

while (!false && true)
{
}

Before people yell at me, its all the same IL code, I checked :)

Allen
jsight
@jsight, heh, that also gets converted to the same IL code :)
Allen
But what about all that unnecessary work you're putting the poor compiler through?
Michael Burr
@Burr, damn you're right, he didn't specify "best" at runtime or compile time lol
Allen
@Michael: I like to see the compiler work for its dinner.
Michael Petrotta
There goes Michael again, talking to himself
Allen
Maybe while (!false || true) - you know, just in case.
Jon B
Moayad Mardini
what about the following: for (;true;) { ... } ?
Venemo
Why should we do something simple if we can do it complicated?!!
serhio
@serhio, it was a joke
Allen
+2  A: 

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
don't worth in .NET, when compiler transforms your (bad readable) *for* without condition in a *while* with condition.
serhio
@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
@Pavel, see Pierre-Alain Vigeant 's answer.
serhio
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
+2  A: 

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
finally, using that we will wait a little more that the programs compile(compile transformation from for=>while)
serhio
A: 

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++) { }
KeeperOfTheSoul
-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
+1  A: 

I know in the C++ world Stroustrup advocates for(;;) in TC++PL, but I don't recall why.

me22
Many C++ compilers warn about the condition never changing in `while(true)`. Maybe that's the reason?
sbi
Loadmaster
A: 

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
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
Its an example for the answer stated before the code :)
George
+6  A: 

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. =)

JohnFx
http://xkcd.com/292/
Callum Rogers
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?
Loadmaster
@Loadmaster: Thanks, I was just throwing it out there as another option, not necessarily endorsing it.
JohnFx
-1 don't use goto in C#, nor in VB.NET: bad practice in modern language.
serhio
@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
@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
@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
@serhio: Hey, thanks for referencing my *goto* article!
Loadmaster
@Loadmaster: Are you David?... a, ok, I see :) good work. However, you convinced not everbody.
serhio
@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.
Loadmaster
A: 

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
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
why waste time and resources declaring a variable when you can use while(true)? It doesn't make sense in my opinion
waqasahmed
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
+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
+1  A: 

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.

Loadmaster
yes, but this is for C, not for C#.
serhio
It works in C#. And the C# language was derived (indirectly) from C.
Loadmaster
+1  A: 

Who cares. It's not like if you stumble across a for(;;) in source control you're going to replace it with a while(true). Arguing this is like arguing brace placement.

Dustin Getz
Trying to start a holy war, are you?
Loadmaster
+2  A: 

Even i also say below one is better :)

while(true)
{

}
anishmarokey
yeah, its better!
Steve
A: 

while(1) { }

Cadoo
That does not work in C# since `Constant value '1' cannot be converted to a 'bool'`
Pierre-Alain Vigeant
A: 

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
if you're golfing then C# is the wrong language anyway.
TokenMacGuy