当在 while 循环的条件后放置一个分号时会发生什么? [英] What happens when one places a semi-colon after a while loop's condition?

查看:39
本文介绍了当在 while 循环的条件后放置一个分号时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到过几次这样的情况:

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

我发现将 ; 用于 "empty block" 空语句是一个 要使用的可疑构造,因为这样的问题:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆