问题描述
在我的程序的一部分,我有代码:
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();
}
当我设置我的程序以使cameraName默认为LAVT Prosilica GT2750(我的调试器将显示它的值),它进入if语句并运行 mCamera = new camera_avtcam_ex_t();
,但是当我走到下一个执行的行我的调试器直接跳到行 mCamera = new camera_qcam_ex_t();
并执行它。考虑到if / else语句的性质,怎么可能发生这种情况呢?
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?
注意:如果我用一个简单的else语句替换else if,就会看到相同的行为。
NOTE: If I replace the else if with just a simple else statement, the same behavior is seen.
推荐答案
由于尝试调试版本构建,您看到了这一点
You are seeing this due to trying to debug a release build
尝试调试debug构建。你应该看到你期望的行为。在调试优化构建时,行不一定与源代码对齐。如你所知,优化器决定最好同时执行这两个并在不需要的情况下抛出一个。
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.
这篇关于为什么我的程序同时进入if语句和相应的else语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!