C ++:虽然循环条件连续执行,但循环体从不执行
C++: While loop condition executes continuously, loop body never executes
这段代码有什么问题?为什么循环条件重复执行而循环体从不执行?这让我发疯!我看不出问题:
bool test() { std::cout << "condition!" << std::endl; return true; }
while(test());
{
std::cout << "This message never appears!!!" << std::endl;
}
输出:
condition!
condition!
condition!
...forever
我当然瞎了,原因是"while"后面的分号错了!编译器认为没有循环体,只是重复执行"nothing"。我读到的循环体,编译器只是认为是一个 un-named/anonymous 范围,在循环之后,所以它永远不会被执行。
这段代码有什么问题?为什么循环条件重复执行而循环体从不执行?这让我发疯!我看不出问题:
bool test() { std::cout << "condition!" << std::endl; return true; }
while(test());
{
std::cout << "This message never appears!!!" << std::endl;
}
输出:
condition!
condition!
condition!
...forever
我当然瞎了,原因是"while"后面的分号错了!编译器认为没有循环体,只是重复执行"nothing"。我读到的循环体,编译器只是认为是一个 un-named/anonymous 范围,在循环之后,所以它永远不会被执行。