How do I view the value of an variable in C++?

On high optimization levels, the compiler can eliminate intermediate values, as you have seen here. There are a number of options:

  • You can reduce the optimization level to make it easier for the debugger to keep track of things. -O0 is certain to work (but will be quite a lot slower), -O1 might work okay as well.
  • You can add some explicit print statements to log the output value.
  • You can also usually force the compiler to retain this specific value by making it volatile (but remember to un-make it volatile when you’re done!). Note, however, that since control flow is also subject to alteration in optimized code, even if you can see the value of the variable, it may not be entirely clear what point in the code you’re at when you’re looking at the variable in question.

Leave a Comment