12.2.5 When Watching a Variable, the Debugger Says Optimized away
Most compilers today are known as optimizing compilers, which means that the compiler will employ
some tricks to reduce the size of your program or speed it up.
Note: This behavior is usually controlled
by the
-On
switches.
The cause of this error is usually trying to debug parts of the code that does nothing. Watching
the variable
a
in the following example may cause this behavior.
int main() { int a = 0; while (a < 42) { a += 2; } }
The reason for a
to be optimized away is obvious as the incrementation of a
does not affect any other part of our code. This example of a busy-wait loop is a prime example of unexpected behavior if you are unaware of this fact.
To fix this, either lower the optimization level used during compilation or preferably declare
a
as volatile
. Another situation where a variable
may be declared volatile is if a variable is shared between the code and ISR1.For a thorough walkthrough of this issue, have a look at Cliff Lawson’s excellent tutorial on this issue.
1
Interrupt Service Routine