Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can i change starting condition in for loop?

Tags:

c++

for-loop

I have this in my code

for (int i=max_position; i<N; ++i) { ... }

however, inside the loop I am going to update the value of max_position, would this affect my for-loop?

like image 990
bbvan Avatar asked Dec 11 '25 05:12

bbvan


2 Answers

From n4296 which is the draft C++14 standard (although every version of C++ and C have had equivalent wording).

The for statement

 for ( for-init-statement condition(opt); expression(opt)) statement

is equivalent to

 {
     for-init-statement
     while ( condition ) {
         statement
         expression ;
     }
 }

except that names declared in the for-init-statement are in the same declarative region as those declared in the condition, and except that a continue in statement (not enclosed in another iteration statement) will execute expression before re-evaluating condition. [ Note: Thus the first statement specifies initialization for the loop; the condition (6.4) specifies a test, made before each iteration, such that the loop is exited when the condition becomes false; the expression often specifies incrementing that is done after each iteration. — end note ]

As you can see, once you have initialized i, modifying variables used in the expression used to initialize it, will have no effect. (This is one of the places where the standard is actually very clear.)

like image 67
Martin Bonner supports Monica Avatar answered Dec 13 '25 19:12

Martin Bonner supports Monica


No, initialization int i = max_position will be executed just once; if you want to affect the loop, try reversing it:

 for (int i = N - 1; i >= max_position; --i) {
   ...
 }

in this backward loop i >= max_position condition will be checked at each iteration.

like image 41
Dmitry Bychenko Avatar answered Dec 13 '25 21:12

Dmitry Bychenko



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!