Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

c# - What happens when one places a semi-colon after a while loop's condition?

I've come across a situation like this a few times:

while (true) {

while (age == 5); //What does this semi-colon indicate?
//Code
//Code
//Code

}

The while(true) indicates that this is an infinite loop, but I have trouble understanding what the semi-colon after the while condition accomplishes, isn't it equivalent to this?:

while (age == 5) { }

//Code
//Code

In other words, does it mean that the while loop is useless as it never enters the block?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
while (age == 5);     // empty statement

is equivalent to

while (age == 5) { }  // empty block

Update: Even if there is no body to execute, doesn't mean that the loop terminates. Instead it will simply loop repeatedly over the conditional (which may have or rely upon side-effects) until it is satisfied. Here is the equivalent form with a goto:

loop:
if (age == 5)
  goto loop;

This construct is sometimes used as a busy-loop waiting on a flag to be changed in threaded code. (The exact use and validity varies a good bit by language, algorithm, and execution environment.)

I find the use of ; for an "empty block" empty statement a questionable construct to use because of issues like this:

while (age == 5); {
   Console.WriteLine("I hate debugging");
}

(I have seen this bug several times before, when new code was added.)

Happy coding.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...