An answer to the question posted a little while back
Let’s look at the first program to begin:
int main(int argc, char *argv[])
{
char input = 'c';
if (input == 'c')
{
puts("Always");
}
else
{
puts("Never");
}
return 0;
}
It is possible to say that this program will always print “Always” when run. Static analysis occurs on an optimised run of a compiler. What happens when this is compiled with:
g++ Always.cpp -O0 -o Always.exe
With all optimisation turned off (the default) g++ leaves in the possible paths, albeit to dead code. G++ will leave in the check if ‘c’ == ‘c’ and waste cycles. Seen here: What about when compiled with:
g++ Always.cpp -O3 -o OptimisedAlways.exe
The flag -O3 enables all the optimisation methods available in G++ from -O1 to -O3 inclusive.
With this newly optimised exe the final result looks like the following:
Notice that is hasn’t included a possible path the the “Never” call, in fact it’s completely optimised it out and could never product the “Never” result. Now we know how the compiler’s optimisation stage can alter how we expect to see code we can now ask the follow up question.
What would the compiler do to the following code when the optimisation flags have been set?… (-O3):
int main(int argc, char *argv[])
{
char input = getchar();
if (input == 'c')
{
puts("Always");
}
else
{
puts("Never");
}
return 0;
}