skiwi
skiwi

Reputation: 69249

How could this bool method compile without errors?

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?

Upvotes: 2

Views: 119

Answers (4)

James Kanze
James Kanze

Reputation: 153899

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.

Upvotes: 0

Jonathan Potter
Jonathan Potter

Reputation: 37122

Do you have warnings turned off? For me, in VS2012 a similar function produces:

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

Upvotes: 2

Salgar
Salgar

Reputation: 7775

The behaviour is undefined. This should be an error in compilers but never is. You should turn on warnings for your compiler.

Read about exactly why it is undefined behaviour here. How do C++ progs get their return value, when a return is not specified in the function?

Upvotes: 1

Mike Seymour
Mike Seymour

Reputation: 254431

The compiler is not required to diagnose that error, since in general it's impossible for static analysis to determine whether a sufficiently complicated function can run off the end. Instead, you get undefined behaviour.

Hopefully, your compiler will give a warning in this case, if you have warnings enabled.

Upvotes: 3

Related Questions