Why is my program going into both an if statement AND its corresponding else statement?

这一生的挚爱 提交于 2020-01-03 03:10:14

问题


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 have set up my program so that cameraName defaults to L"AVT Prosilica GT2750" (and my debugger will show this to be its value), it goes into the if statement and runs mCamera = new camera_avtcam_ex_t();, but then when I step to the next executed line my debugger skips directly to the line mCamera = new camera_qcam_ex_t(); and executes it. How can this possibly be happening given the nature of if/else statements?

NOTE: If I replace the else if with just a simple else statement, the same behavior is seen.


回答1:


You are seeing this due to trying to debug a release build

Try debugging a "debug" build. You should see the behavior you are expecting. When debugging an optimized build the lines don't necessarily 'line up' with the source code. For all you know, the optimizer decided that it was best to execute both of those and throw one away if it wasn't needed.

Note - I am not suggesting the optimizer did do that, I am just saying it is possible and that you may actually be seeing what line is being executed next. The optimizer is free to reorder the code, unroll loops, propogate constants, remove variables add temporaries, etc, etc, etc.

Edit - additional thoughts
When you get down to the hardware level things can get really reordered. The hardware may choose to execute both sides of a branch before it figures out which one should be taken so that the answer is ready as soon as it is needed. It will do that even though it means throwing other work away as that may yield faster execution.



来源:https://stackoverflow.com/questions/16305637/why-is-my-program-going-into-both-an-if-statement-and-its-corresponding-else-sta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!