Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the correct C# infinite loop, for (;;) or while (true)? [closed]

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?

like image 960
Bob Kaufman Avatar asked Sep 09 '09 18:09

Bob Kaufman


People also ask

What is C structure size?

a) C structure is always 128 bytes.

What is a function in C Mcq?

a) A Function is a group of c statements which can be reused any number of times. b) Every Function has a return type. c) Every Function may no may not return a value.


1 Answers

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.

like image 183
Pierre-Alain Vigeant Avatar answered Oct 07 '22 16:10

Pierre-Alain Vigeant