Yesterday, I had an interview. There they asked me when the code optimization happens?
Say,
int abc;//Global variable
abc = 3;
if(abc == 3)
{
printf("abc will be always 3");
}
else
{
printf("This will never executed");
}
Now the question is when the optimization happens?
A… At Run time
B… At compile time.
I answered at compile time… To me I thought, compiler checks for volatile keyword at compile time. If the variable is not declared as volatile then it optimizes the code. But, when the compiler comes to know that, this variable is never ever going to be other than 3?
If it is at run-time, then when compiler comes to know that variable is never ever going to be other than 3? Because if the variable is going to be changed after this part of the code executed. Please clear my doubt
Most code optimization can’t happen at runtime, at least not how you mean. The code can’t change during execution to reflect a new or different set of variables, that would just make an absolute mess.
What can be done at runtime is choosing the best path through the code, but that has to be done mostly manually in order to create the separate paths, early outs, branches and so on to allow optimization.
Code like this is, as written, allows compile-time optimization because the compiler can check for any possible alternate values of
abcand, if none are found, optimize out the call. The scope of the search greatly influences whether that can happen, however, and the compiler settings influence that.If the compiler is simply naively optimizing single object files and your second line is in another file from the print section, then it may not be able to guarantee
abcdoesn’t change, and so won’t be able to optimize this at all. Regardless of variable use, it depends on how aggressive your compiler settings are and whether they are allowed to discard dead branches, or will consider doing so. Optimizing for size may be more likely to remove the branch than for speed, but medium/high settings will likely do it either way (if possible).Most modern compilers have a whole-program-optimization option, which delays much of the optimization until the linker stage. This allows it to search the whole program, potentially discover that
abcis never changed or used anywhere else, and remove the variable and failing branch from the condition. Whole program optimization can be far more effective than separate optimization for each object, because it can allow more accurate searching.In the case where it’s not possible for the compiler to trim dead code, you can either hint it (recent constructs such as
constexprcan help with that) or add optimizations yourself. It could be as simple as putting the most-likely path first and including a return before the else, saving the CPU from doing a jump. That sort of micro-optimization is unlikely to be necessary, certainly not in a simple example like this, where theifis plenty optimization by itself.