如果在while循环的条件后放置分号,会发生什么情况? [英] 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
}
while(true)
表示这是一个无限循环,但是我很难理解while
条件完成后的分号,这不等于吗?:
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
换句话说,这是否意味着while
循环是无用的,因为它永远不会进入该块?
In other words, does it mean that the while
loop is useless as it never enters the block?
推荐答案
while (age == 5); // empty statement
等同于
while (age == 5) { } // empty block
更新:即使没有要执行的主体,也不意味着循环终止.取而代之的是,它将简单地反复遍历条件(可能具有或依赖于副作用),直到满足条件为止.这是带有goto
的等效形式:
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.)
快乐的编码.
这篇关于如果在while循环的条件后放置分号,会发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!