Is the following code safe and defined in the standard? Will 'i' be incremented by 2 if 'condition' is true?
for (size_t i = 0; i < 100; i++) {
do_something;
if (condition)
i++;
}
Of course. There is nothing wrong with it - syntactically. You can even do something like this:
int i = 0;
for (;;) {
if (i >= 100) {
break;
}
++i;
}
This code is equivalent to
int i = 0;
while(true) {
if (i >= 100) {
break;
}
++i;
}
And furthermore - you can place practically any valid code into the for statement. E.g.
for (do_something_begin(); some_condition(); do_something_end()) {
CODE;
}
and what compiler does with this code is something like this:
do_something_begin()
while (some_condition()) {
CODE;
do_something_end();
}
foris mostly a syntactic sugar for awhileloop.