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.
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) {
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.
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.
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.
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.
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