Hello,
With these two questions as background (first and second), I got curious about how much optimization a C++ compiler can perform when dealing with pointers? More specifically, I'm interested in how smart a compiler is when it optimizes away code which it may detect will never be run.
(Some may point out that this is a dupe of this question, which it may be, but this particular part of it was not entirely answered. So therefore I decided to start a new question which deals only with this concern.)
(I'm not a C++ expert, so I may be wrong in the following statements, but I'll give it a shot anyway). A C++ compiler may optimize away portions of code which it will recognize never to be executed or never exited (such as loops). Here is an example:
void test() {
bool escape = false;
while ( !escape ); // Will never be exited
// Do something useful after having escaped
}
The compiler would most likely recognize that the loop will never be exited as the code never changes the value of escape
so that the loop is exited. This makes the loop useless.
Now, if we were to change the variable to a pointer, would the compiler still optimize away the loop? Say the code looks like so:
void test( bool* escape ) {
while ( *escape ); // Will this be executed?
// Do something useful after having escaped
}
My suspicion is that the compiler will do away with the loop, or else the keyword volatile
would be redundant, yes?. But what about when working with threads -- where it is in fact modified but outside the function, and maybe even outside that C++ file entirely -- would the compiler still remove the loop? Does it make a difference if the variable pointed to by escape
is a global variable, or a local variable inside another function? Can the compiler make this detection? In this question, some say that the compiler will not optimize the loop if library functions are invoked inside the loop. What mechanisms are then in place when using library functions which prevent this optimization?