Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would the compiler optimize this for loop?

In C or C++, if the compiler encounters a for loop in which a counter is counting from 0 to n, and n is a variable (not a function call, and NOT A CONSTANT either), would the compiler optimize the loop by checking if the variable n (the bound variable) will be changed during the loop (accessed for write, eg: n can be a length of a string that is calculated before the loop), by optimizing here I mean copying its value to a register to avoid memory access?

Here is an example:

for (int c = 0; c < n; c++) {
    // do something not related to n
}

would the compiler notice that and optimize it?

like image 917
Hassen Dhia Avatar asked Apr 17 '26 12:04

Hassen Dhia


2 Answers

would the c/c++ compiler optimize the loop by checking if the variable n ( the bound variable ) will be changed during the loop

The "as-if" rule allows the compiler to reorder or re-write code as long as the observable effect is "as if" it executed the code you wrote.

The keyword here is "observable". Unless it can be proven that n cannot change during execution of the body of the loop, then the loop must re-evaluate c < n for each iteration.

If the compiler has access to all the code in the loop (for example, it's defined in the same compilation unit, or a global optimisation has another look during linking, n is never aliased by a reference or pointer) then it may well be in a position to prove that n does not change.

In that case, you should not be surprised to see the loop optimised in some way.

like image 85
Richard Hodges Avatar answered Apr 20 '26 01:04

Richard Hodges


The result depends on the compiler in use.

A compiler could use a processor register for n and you can still modify n within the loop. So minimal optimization is possible anyway.

Placing the value of the variable in a processor register may cause an 'aliasing' problem if you have a pointer pointing to n and you change the value of n indirectly using a pointer.

For example:

int n = 4;
int *nptr = &n;
for(int i = 0; i < n; ++i)
  --*nptr;

The compiler has to know that nptr is an alias for n and therefore n must be read from memory on every access but in many cases the compiler simply has no chance of knowing the relationship between n and nptr.

You can use the volatile keyword to stop the compiler from optimizing the variable (i.e. volatile int n = 4;)

like image 20
Andreas H. Avatar answered Apr 20 '26 00:04

Andreas H.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!