2

I have this method in my C++ program, in Visual Studio 2012, standard compiler:

bool FPS::frameRenderingQueued(const Ogre::FrameEvent &evt) {
    bool result = BaseApplication::frameRenderingQueued(evt);
    if (!result) {
        Ogre::LogManager::getSingleton().logMessage("Exiting, result of frame rendereing queued: " + result);
        return result;
    }
    for (int x = 0; x < 20; x++) {
        for (int z = 0; z < 20; z++) {
            robotAnimation[x][z]->addTime(evt.timeSinceLastFrame);
            tileSceneNode[x][z]->translate(tileSceneNode[x][z]->getOrientation() * Ogre::Vector3::UNIT_X * 35.0f * evt.timeSinceLastFrame);
        }
    }
}

How could it compile without giving any errors? I mind you that the result cannot be predictable.

When I ran it, this happened: The function itself returned false (as Ogre shuts down if frameRenderingQueued() returns false. However the branch if (!result) { ... } has never been reached. So the behaviour was unpredictable.

Later when I added return true; at the end of the function, everything was working as expected.

So how could this broken method compile just fine?

4

4 回答 4

3

编译器不需要诊断该错误,因为通常静态分析不可能确定一个足够复杂的函数是否可以运行结束。相反,您会得到未定义的行为。

如果您启用了警告,希望您的编译器会在这种情况下发出警告。

于 2013-10-16T10:09:28.967 回答
2

你有关闭警告吗?对我来说,在 VS2012 中,类似的功能会产生:

warning C4715: 'frameRenderingQueued' : not all control paths return a value

于 2013-10-16T10:10:27.660 回答
1

行为未定义。这应该是编译器中的错误,但绝不是。您应该为您的编译器打开警告。

在此处阅读有关其未定义行为的确切原因。 当函数中没有指定返回值时,C++ progs 如何获得它们的返回值?

于 2013-10-16T10:09:41.030 回答
0

Running off the end of a non-void function is undefined behavior. That means that the compiler is not required to issue a diagnostic, and that it must compile the code unless it can prove that you must inevitably run off the end, which is usually impossible. (Imagine, for example, that BaseApplication::frameRenderingQueued always returns false, or that the function you call with tileSceneNode[x][z]->translate(...) always throws an exception.)

Most compilers will warn about code like the above. You should activate the warnings, and pay attention to them.

于 2013-10-16T10:12:52.647 回答