When Watching a Variable, the Debugger says Optimized away

Most compilers today are what is known as an optimizing compiler. This 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. Trying to watch 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. Other situations where a variable should be declared volatile is if some variable is shared between the code and an ISR1.

For a thorough walkthrough of this issue, have a look at Cliff Lawson’s excellent tutorial on this issue.

1

Interrupt Service Routine