【发布时间】:2020-12-09 04:33:33
【问题描述】:
为什么我可以这样做:
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++17 中对 if() 进行更改时,可能没有人提议对 while() 进行更改相关:https://en.cppreference.com/w/cpp/language/if
-
while statement with initializer 回答你的问题了吗?
-
顺便说一句,最后一个 sn-p 的写法是
while(int result; result = getValue() && result > 100) {}。我不确定您是否使用 while-with-initializer 描述了相同的语义。 -
@cigien,如果
result的期望值为0,我认为它不会起作用,因为它不会检查第二个条件。
标签: c++ if-statement while-loop c++17 c++20