Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 463
HelloGoodbye Avatar asked Oct 16 '25 05:10

HelloGoodbye


2 Answers

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.

like image 93
NPE Avatar answered Oct 19 '25 10:10

NPE


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
}
like image 23
Paul R Avatar answered Oct 19 '25 10:10

Paul R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!