Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C or C++ : for loop variable

Tags:

c++

c

for-loop

My question is a very basic one. In C or C++:

Let's say the for loop is as follows,

for(int i=0; i<someArray[a+b]; i++) {
 ....
 do operations;
}

My question is whether the calculation a+b, is performed for each for loop or it is computed only once at the beginning of the loop?

For my requirements, the value a+b is constant. If a+b is computed and the value someArray[a+b]is accessed each time in the loop, I would use a temporary variable for someArray[a+b]to get better performance.

like image 910
SKPS Avatar asked Nov 13 '13 14:11

SKPS


People also ask

Can you declare a variable in a for loop in C?

In C and C++, there are currently two places you can declare a variable “in a for loop:” in the for statement itself, and in the statement it controls (loops). Consider: for (int i = 0; i < 42; ++i) {

What is a loop variable in C?

In for loop, a loop variable is used to control the loop. First, initialize this loop variable to some value, then check whether this variable is less than or greater than the counter value. If the statement is true, then the loop body is executed and the loop variable gets updated.

Can a for loop be a variable?

In computer programming, a loop variable is a variable that is set in order to execute some iterations of a "for" loop or other live structure.

Does C have a for loop?

In programming, a loop is used to repeat a block of code until the specified condition is met. C programming has three types of loops: for loop. while loop.


1 Answers

You can find out, when you look at the generated code

g++ -S file.cpp

and

g++ -O2 -S file.cpp

Look at the output file.s and compare the two versions. If someArray[a+b] can be reduced to a constant value for all loop cycles, the optimizer will usually do so and pull it out into a temporary variable or register.

like image 186
Olaf Dietsche Avatar answered Oct 27 '22 12:10

Olaf Dietsche