HelloGoodbye
HelloGoodbye

Reputation: 3912

How to prevent compiler from optimizing away breakpoint?

I have written an if-clause that checks whether I should break the program for debugging or not:

if (a < 0) {
    a = a;
}

a should not become negative, but I have found that it does, and I want to break for debugging to see why it becomes negative if that happens, hence I have written this if-clause. On the line a = a; I have set a breakpoint, which is supposed to stop the program if it enters the if-clause. The thing is that the line doesn't do anything (which is necessary in order not to mess anything up), so the line is optimized away and the breakpoint ends up after the if-clause. This trick usually works but apparently the compiler wasn't very found of it this time.

The language is C++, and I'm compiling with qmake (a Qt tool) and mingw.

My question is, how can I prevent the compiler from optimizing away lines of code when I have breakpoints set on them? Or is there some other way to conditionally break the program for debugging?

Upvotes: 4

Views: 3036

Answers (5)

Brian Nixon
Brian Nixon

Reputation: 9838

It’s not portable, but with MSVC I use __asm nop (surrounded by #ifndef NDEBUG#endif if the code is likely to remain in place for a while) to insert a literal no-op that I know the compiler won’t touch.

Upvotes: 1

Alexey Frunze
Alexey Frunze

Reputation: 62096

If it's C or C++, simply defining a as volatile should help.

Upvotes: 2

HelloGoodbye
HelloGoodbye

Reputation: 3912

I defined a NO_OP() macro which doesn't do anything and doesn't require the file that's using it to include any header files:

#define  NO_OP()  {float f = 0; if (f != 0) exit(0);}

I don't know if the compiler will be able to optimize this macro away, but it works for me with MinGW.

Upvotes: 1

NPE
NPE

Reputation: 500703

One possibility is to call an I/O function. In Java, one could write:

if (a < 0) {
    System.out.printf("");
}

Similarly, in C/C++, one could write:

if (a < 0) {
    printf("");
}

Even though the function call is effectively a no-op, the compiler doesn't know that, and is unlikely to optimize the call away.

Or is there some other way to conditionally break the program for debugging?

Many modern IDE allow one to set conditional breakpoints: Visual Studio, Eclipse.

Upvotes: 3

Paul R
Paul R

Reputation: 213060

I usually put a printf (or cout, or whatever is appropriate for the language that you are using) here so that I can set a breakpoint, e.g.

if (a < 0) {
    printf("a < 0 !\n"); // <<< set breakpoint here
}

Upvotes: 2

Related Questions