In C++ changing a loop variable inside a for-loop is allowed:
for( int i = 0; i < limit; i++ ) {
if( condition ) {
i--;
}
}
Now if a loop body is rather complex it is not immediately obvious to the reader whether the loop variable is changed inside the loop body. It would be nice to somehow tweak the code so that once the reader only sees the for-loop header he immediately knows that the loop variable is not changed inside the body.
For example, if I use const
:
const int value = computeValue();
//lots of code here
then it is clear that whatever code is written below the const
variable definition the variable is unchanged.
Is there a way to achieve something similar - logical constness within the iteration - in case of for-loop control variables in C++?
Yes, they are destroyed when they go out of scope. Note that this isn't specific to variables in the loop. This rule applies to all variables with automatic storage duration. Save this answer.
Answer: The significance of updating the loop control variable in while statements is that it helps to terminate the loop. Explanation: Loops are used when a part of the code is to be repeated n number of times.
A common use of loops is the one in which the loop makes use of a variable (called control variable) that at each iteration is changed by a constant value, and whose value determines the end of the loop. Example: Print the squares of the integers between 1 and 10.
Another method of performing looping in your scripts is by using the For-EndFor looping statements. Similar to a While loop, a For loop consists of three parts: the keyword For that starts the loop, the condition being tested, and the EndFor keyword that terminates the loop.
I don't think this is possible for hand-crafted loop, but I'd guess that could be considered an additional argument to encourage the use of std::for_each and BOOST_FOREACH for iterations over STL container.
EDIT ... and the C++0x range-based for-loop (thanks Matthieu. M :)
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