首页 > 解决方案 > 为什么我们可以在 if 中使用分号,但在 while 循环中却没有

问题描述

为什么我可以这样做:

if (int result=getValue(); result > 100) {
}

但不能这样做:

while (int result=getValue(); result > 100) {
}

为什么要歧视while?条件就是条件。为什么while不能像if可以一样评估它?

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

int result = getValue();
while (result > 100) {
    //do something
    result = getValue();
}

标签: c++if-statementwhile-loopc++17c++20

解决方案


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

for (int result=getValue(); result > 100;) {
}

推荐阅读