Reputation: 4646
Very frequently, I want to test the value of a variable in a function via a breakpoint. In many cases, that variable never actually gets referenced by any code that "does stuff", but that doesn't mean I don't still want to see it. Unfortunately, the optimizer is working against me and simply removing all such code when compiling, so I have to come up with convoluted grossness to fool the compiler into thinking those values actually matter so they don't get optimized away. I don't want to turn the optimizer off, as it's doing important stuff in other places, but just for this one block of code I'd like to temporarily disable it for the sake of debugging.
Upvotes: 5
Views: 2065
Reputation: 70502
If the only purpose of the variable is to be viewed while in a breakpoint with a debugger, you can make the variable global. You could, for instance, maintain a global buffer:
#ifdef DEBUG
char dbg_buffer[512];
template <typename T>
void poke_dbg (const T &t) {
memcpy(dbg_buffer, &t, sizeof(T));
}
#else
#define poke_dbg(x)
#endif
Then during debugging, you can inspect the contents of the dbg_buffer (with an appropriate cast if desired).
Upvotes: 0
Reputation: 263617
Here's an example of a trick I've used:
#include <ctime>
#include <iostream>
int main() {
std::cout << "before\n";
if (std::time(NULL) == 0) {
std::cout << "This should not appear\n";
}
std::cout << "after\n";
}
The time()
call should always return a positive value, but the compiler has no way of knowing that.
Upvotes: 1
Reputation: 320719
Code the produces observable behavior fits the requirements by definition. For example, printf("")
.
Access to volatile variable also formally constitutes observable behavior, although I won't be surprised if some compilers still discarded "unnecessary" volatile variables.
For this reason, a call to an I/O function appears to be the best canditate to me.
Upvotes: 4
Reputation: 21351
You do not specify your compiler so I will just add here that I have been using the volatile specifier on any variables that I use specifically for debugging. In my compiler (Embarcadero RAD Studio C++ Builder) I have been using this for a couple of years and not once has the variable been optimized out. Maybe you don't use this compiler, but if you do I can say volatile has certainly always worked for me.
Upvotes: 0
Reputation: 86
You can try "volatile" keyword. Some intro is at http://en.wikipedia.org/wiki/Volatile_variable .
Generally speaking, the volatile keyword is intended to prevent the compiler from applying any optimizations on the code that assume values of variables cannot change "on their own."
Upvotes: 1
Reputation: 258648
Have you tried
#pragma optimize("",off)
?
MSVS specific I think - http://msdn.microsoft.com/en-us/library/chh3fb0k(v=vs.80).aspx
Upvotes: 0