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?
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)) statementis 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
continuein 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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With