Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show that a loop control variable is not changed inside the C++ for-loop body?

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++?

like image 216
sharptooth Avatar asked Nov 23 '10 11:11

sharptooth


People also ask

What happens to variable after for loop?

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.

What is the significance of updating loop control variable in while statement?

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.

What is control variable in looping statements?

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.

What three items do we need to include when using a looping structure to avoid an infinite loop?

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.


1 Answers

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 :)

like image 180
icecrime Avatar answered Oct 22 '22 03:10

icecrime