为什么我们可以在 if 循环中使用分号,而在 while 循环中不能使用分号

arm*_*ali 0 c++ if-statement while-loop c++17 c++20

为什么我可以这样做:

if (int result=getValue(); result > 100) {
}
Run Code Online (Sandbox Code Playgroud)

但不能这样做:

while (int result=getValue(); result > 100) {
}
Run Code Online (Sandbox Code Playgroud)

为什么要歧视while?条件就是条件。为什么while不能像ifcan那样评价它?

为了使用 实现所需的行为while,我必须以这种方式实现它:

int result = getValue();
while (result > 100) {
    //do something
    result = getValue();
}
Run Code Online (Sandbox Code Playgroud)

Bar*_*rry 11

因为我们已经有了一个带有初始化器的 while 循环。它的拼写是:

for (int result=getValue(); result > 100;) {
}
Run Code Online (Sandbox Code Playgroud)

  • 难道提议的语法不想在每次迭代时评估 *init-statement* 吗? (4认同)
  • @armanali如果你不想循环,那么为什么要使用`while`? (3认同)
  • 您的编辑不会改变任何内容。`for` 仍然可以完成工作。 (2认同)