在阅读了关于 C/C++ 中逗号运算符的一个很好的答案后(逗号运算符是做什么的- 我使用相同的示例代码),我想知道哪种是实现 while 循环的最易读、可维护、首选的方法。特别是一个while循环,其条件取决于操作或计算,并且第一次条件可能为假(如果循环总是至少通过一次,那么do-while就可以正常工作)。
逗号版本是最喜欢的吗?(每个答案怎么样,其余的可以通过相应的投票来投票?)
简单的实现
此代码具有重复的语句,(很可能)必须始终相同。
string s;
read_string(s); // first call to set up the condition
while(s.len() > 5) // might be false the first pass
{
//do something
read_string(s); // subsequent identical code to update the condition
}
使用break实现
string s;
while(1) // this looks like trouble
{
read_string(s);
if(s.len() > 5) break; // hmmm, where else might this loop exit
//do something
}
使用逗号实现
string s;
while( read_string(s), s.len() > 5 )
{
//do something
}