Disclaimer: I tried to find a similar question, however this came back to every question in C ++ ... I would also be grateful to everyone who could offer a better headline.
C ++ has two outstanding loop structures: while and for .
- I deliberately ignore the
do ... while construct, it's kind of unprecedented - I know
std::for_each and BOOST_FOREACH , but not every loop is for each
Now I can be a little tight, but I always need to fix the code as follows:
int i = 0; while ( i < 5) {
And convert it to:
for (int i = 0; i < 5; ++i) {
The for advantages in this example are several, in my opinion:
- Locality : the variable I lives only in the loop area
- Pack : the "control" loop is packed, so just looking at the declaration of the loop, I can understand whether it is correctly formed (and will be completed ...), assuming, of course, that the loop variable does not change in the body of the body
- It can be embedded, although I would not always advise it (which leads to complex errors)
I have a tendency not to use while , with the possible exception for the while(true) idiom, but that’s not what I used for a while (pun intended). Even in difficult conditions, I tend to stick with the for construct, although on a few lines:
// I am also a fan of typedefs for (const_iterator it = myVector.begin(), end = myVector.end(); it != end && isValid(*it); ++it) { /* do stuff */ }
You can do this with while , of course, but then (1) and (2) will not be checked.
I would like to avoid “subjective” comments (like “I like it / better”), and I'm definitely interested in referring to existing coding rules / coding standards.
EDIT :
I try, as far as possible, to adhere to (1) and (2), (1), because it is recommended to localize the location → C ++ Encoding standards: Clause 18 and (2), because it simplifies maintenance if I do not need to scan the whole body loop to look for possible changes to the control variable (which I take for granted with for when the Third expression refers to loop variables).
However, as shown below, gf , although it has its own application:
while (obj.advance()) {}
Please note that this is not a claim to while , but an attempt to find which of while or for use depending on the case (and for reasons of common sense, and not just like it).