3

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++;
}
3
  • 6
    Yes, it is. And it is common to write such things. for is mostly a syntactic sugar for a while loop. Commented Oct 1, 2014 at 13:09
  • 1
    yes,undoubtdly...it is the general flow of the program,no special case Commented Oct 1, 2014 at 13:11
  • 1
    IMO, not because it is allowed in the standard and that it works makes it safe (and/or easy to maintain in the long run). Commented Oct 1, 2014 at 13:12

3 Answers 3

4

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();
} 
Sign up to request clarification or add additional context in comments.

2 Comments

And yes - I am aware of the fact, that it is not exactly the same as what compiler does (variable scope of do_something_begin() is just wrong) but for educational reasons I find it better to keep it like this.
It's worth pointing out that in some other languages it is illegal to modify the loop counter within the loop, and that outside the loop the loop counter's value is undefined (regardless of the variable scope). C/C++ isn't like this. Don't let the fact it is illegal in other languages put you off doing it in C/C++.
0

If I starts at 0 and the condition is true then i=1, then when the loop iterates again i will be increased by 1 to 2 so yes.

Comments

0

You just wrote

size_t i = 0;

while (i < 100) {
    do_something;
    if (condition)
        i++;
    i++;
}

This is perfectly legal. If I were you I would add a comment saying "Skip the next one".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.