【发布时间】:2013-05-15 19:21:33
【问题描述】:
这是我的代码:
int main()
{
int input;
bool isZero = false;
while (!isZero)
{
...
if (0 == input)
{
isZero = true;
}
else
{
isZero = false;
}
}
return 0;
}
程序做了它应该做的事情,但我觉得 !isZero 表达式并不是万无一失的。
是
bool isZero = false;
while(!isZero);
{
....
}
和
一样bool isZero = false;
while(isZero == false)
{
...
}
为什么或为什么不? 还有,在哪些情况下真代表1,在哪些情况下代表任何非零数?
【问题讨论】:
-
while (input)怎么样?根本不需要isZero。 -
true是任何非零或转换为非零的东西。 -
它们是一样的,我更喜欢
while(!isZero) -
你也可以说
while((izZero == false) == true)。别等了,这还不够万无一失!让它while(((izZero == false) == true) != false)。不用等... -
@chris
while(input)在技术上是可行的,但在这种特殊情况下,我宁愿明确检查它:while (input != 0)。主要是因为程序员的意图会更清楚——读者不必知道某些特定的语言规范,例如int-to-bool转换。除此之外,将ints 视为bools 是非常C 风格的IMO。
标签: c++ while-loop boolean