Teague Teague - 14 days ago 7
C Question

How much do C/C++ compilers optimize conditional statements?

I recently ran into a situation where I wrote the following code:

for(int i = 0; i < (size - 1); i++)
{
// do whatever
}

// Assume 'size' will be constant during the duration of the for loop


When looking at this code, it made me wonder how exactly the for loop condition is evaluated for each loop. Specifically, I'm curious as to whether or not the compiler would 'optimize away' any additional arithmetic that has to be done for each loop. In my case, would this code get compiled such that (size - 1) would have to be evaluated for every loop iteration? Or is the compiler smart enough to realize that the 'size' variable won't change, thus it could precalculate it for each loop iteration.

This then got me thinking about the general case where you have a conditional statement that may specify more operations than necessary.

As an example, how would the following two pieces of code compile:

if(6)

if(1+1+1+1+1+1)

int foo = 1;
if(foo + foo + foo + foo + foo + foo)


How smart is the compiler? Will the 3 cases listed above be converted into the same machine code?

And while I'm at, why not list another example. What does the compiler do if you are doing an operation within a conditional that won't have any effect on the end result? Example:

if(2*(val))

// Assume val is an int that can take on any value


In this example, the multiplication is completely unnecessary. While this case seems a lot stupider than my original case, the question still stands: will the compiler be able to remove this unnecessary multiplication?

Question:


  • How much optimization is involved with conditional statements?

  • Does it vary based on compiler?


Answer

The C++ language specification permits the compiler to make any optimization that results in no observable changes to the expected results.

If the compiler can determine that size is constant and will not change during execution, it can certainly make that particular optimization.

Alternatively, if the compiler can also determine that i is not used in the loop (and its value is not used afterwards), that it is used only as a counter, it might very well rewrite the loop to:

for(int i = 1; i < size; i++)

because that might produce smaller code. Even if this i is used in some fashion, the compiler can still make this change and then adjust all other usage of i so that the observable results are still the same.

To summarize: anything goes. The compiler may or may not make any optimization change as long as the observable results are the same.

Comments