【发布时间】:2016-06-26 23:46:45
【问题描述】:
在阅读了关于 C/C++ 中逗号运算符的精彩回答(What does the comma operator do - 我使用了相同的示例代码)之后,我想知道哪种方式是实现 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
}
【问题讨论】:
-
使用do-while模式,在开始执行
read_string,在最后测试条件。 -
你们俩都忘记了“做某事”,我猜应该在
read_string之后执行,并且只有条件通过。 -
@Cody Gray:我不清楚吗?如果第一次条件中的代码为假(并且循环不应该进入),这不会处理这种情况。
-
我通常不喜欢逗号运算符的小“技巧”,但在这种情况下,鉴于
read_string的设置方式,我会投票给#3。while( reading a line succeeds ) { do something with the line }模式是一种非常强大、可读、自然且常见的模式,值得坚持使用。但是,更值得重写read_string函数以便可以直接使用它的返回值。 -
投票重新开放。虽然这在某种程度上确实涉及到意见,但对于如何使这样的代码具有可读性的问题有足够的事实基础,因此这是一个有价值的问题,可以产生有意义的答案。
标签: c++ c while-loop break comma-operator