views:

90

answers:

5

I have something analogous to the following code...

void function(int x)
{
    // complicated operation on x
    blah 
    blah
}

It all appears to be working fine except when x happens to be a particular value, say "273". But x being 273 is a rare event, 99.999% of the time it is some other value. Now I wish to observe the events when this function is called with x=273, so I would like to insert a breakpoint that gets hit only with x is that value. Perhaps I could do it like this:

void function(int x)
{
    if (x == 273)
    {
        // put breakpoint on this line.
    }
    // complicated operation on x
    blah 
    blah
}

The problem is that presumably the compiler will optimise away this "if" statement because it doesn't do anything. So my question is what should I put within the "if" statement to to make sure it gets compiled in to something... or should I be tracing the x==273 case in some completely different way.

+3  A: 

Maybe just use a conditional breakpoint? Have a look here how to set it up.

Michal Sznajder
I didn't think they existed in VS2008
Mick
They do, give it a shot, it will work wonders for you.
Matthew Vines
+8  A: 

It sounds like what you're looking for is conditional breakpoints. These are a feature of Visual Studio which allow a break point to only be hit when a very specific condition is true.

To do this, put a break point at the start of the function. Then right click on it and select "Condition". Then add following expression

x == 273

Now you can debug this without changing your source binary.

JaredPar
Wow! How did I not know that!..
Mick
A: 

Create new conditional breakpoint (right click breakpoint and select "Condition...") and put

x == 273

as a condition.

Alex T.
A: 
if (x == 273)
{
    volatile int tmp = 0; // This is not get optimized
}
Nicolas Viennot
A: 

In cases when I need a real line to set a breakpoint to i use something similar:

{
   int i = 42;
}

It get optimized away but I may get a compiler warning for unused variable. But a conditional breakpoint (other answers) is probably better in this case

Arve