Why is my program included in both the if statement and its corresponding else statement?

In part of my program, I have the code:

if(cameraName == L"AVT Prosilica GT2750") { mCamera = new camera_avtcam_ex_t(); } else if(cameraName == L"QImaging Retiga 2000R\\4000R") { mCamera = new camera_qcam_ex_t(); } 

When I set up my program so that the default camera name is L "AVT Prosilica GT2750" (and my debugger will show that this is its value), it goes into the if statement and runs mCamera = new camera_avtcam_ex_t(); , but then, when I step to the next line executed, my debugger passes directly to the line mCamera = new camera_qcam_ex_t(); and performs it. How can this happen if there are if / else statements?

NOTE. If I replaced the else if with a simple else statement, it will be seen that this behavior is observed.

+1
c ++ debugging if-statement visual-studio-2010
source share
1 answer

You see this because of an attempt to debug release builds

Try debugging the "debug" assembly. You should see the behavior you expect. When debugging an optimized assembly, the lines are not necessarily β€œaligned” with the source code. As far as you know, the optimizer decided that it is best to run both of them and throw it away if it is not needed.

Note. I do not suggest that the optimizer do this, I just say that it is possible, and that you can really see which line is executed next. The optimizer is free to reorder code, unroll loops, maintain constants, delete variables, add temporary ones, etc. Etc. Etc.

Change - Extra Thoughts
When you go to the hardware level, things can become really reordered. The hardware can choose to run both sides of the branch before it finds out which one should be taken so that the answer is ready as soon as necessary. He will do this, even if it means discarding another job, as this may lead to faster execution.

+3
source share

All Articles