After reading a great answer about the comma operator in C/C++ (What does the comma operator do - and I use the same example code), I wanted to know which is the most readable, maintainable, preferred way to implement a while loop. Specifically a while loop whose condition depends on an operation or calculation, and the condition might be false the first time (if the loop were to always pass at least once then the do-while would work fine).
Is the comma version the most preferred? (how about an answer for each, and the rest can vote by upvoting accordingly?)
Simple Implementation
This code has duplicate statements, that (most likely) must always be the same.
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
}
Implementation using 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
}
Implementation using comma
string s;
while( read_string(s), s.len() > 5 )
{
//do something
}