Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra increment within for loop c++

Tags:

c++

for-loop

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++;
}
like image 958
Simmovation Avatar asked Apr 29 '26 17:04

Simmovation


1 Answers

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();
} 
like image 85
Jendas Avatar answered May 01 '26 07:05

Jendas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!