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

﹥>﹥吖頭↗ 提交于 2019-12-29 07:35:11

问题


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?


回答1:


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.




回答2:


while (age == 5); gets stuck into an infinite loop. In c ; is a null terminator. The compiler assumes that the above loop has only one statement that is ; which causes the loop to be iterated over infinitely.




回答3:


a statement consisting of only

;

is a null statement. It is the same as a block (also called compound statement) with nothing inside

{
}

They both perform no operations.




回答4:


If we put ; anywhere it means null statement (statement that does nothing).

When we write

while(true);

It means a while loop an a statement that does nothing. It is similar to the

while(true)
i++;

Here statement is not null but in the previous case statement was null.



来源:https://stackoverflow.com/questions/8706139/what-happens-when-one-places-a-semi-colon-after-a-while-loops-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!