Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I tell the compiler to consider a control path closed with regards to return value?

Say I have the following function:

Thingy& getThingy(int id)
{
    for ( int i = 0; i < something(); ++i )
    {
        // normal execution guarantees that the Thingy we're looking for exists
        if ( thingyArray[i].id == id )
            return thingyArray[i];
    }

    // If we got this far, then something went horribly wrong and we can't recover.
    // This function terminates the program.
    fatalError("The sky is falling!");

    // Execution will never reach this point.
}

Compilers will typically complain at this, saying that "not all control paths return a value". Which is technically true, but the control paths that don't return a value abort the program before the function ends, and are therefore semantically correct. Is there a way to tell the compiler (VS2010 in my case, but I'm curious about others as well) that a certain control path is to be ignored for the purposes of this check, without suppressing the warning completely or returning a nonsensical dummy value at the end of the function?

like image 587
suszterpatt Avatar asked Aug 27 '12 17:08

suszterpatt


2 Answers

You can annotate the function fatalError (its declaration) to let the compiler know it will never return.

In C++11, this would be something like:

[[noreturn]] void fatalError(std::string const&);

Pre C++11, you have compiler specific attributes, such as GCC's:

void fatalError(std::string const&) __attribute__((noreturn));

or Visual Studio's:

__declspec(noreturn) void fatalError(std::string const&);
like image 200
Matthieu M. Avatar answered Oct 21 '22 07:10

Matthieu M.


Why don't you throw an exception? That would solve the problem and it would force the calling method to deal with the exception.

If you did manage to haggle the warning out some way or other, you are still left with having to do something with the function that calls getThingy(). What happens when getThingy() fails? How will the caller know? What you have here is an exception (conceptually) and your design should reflect that.

like image 35
anio Avatar answered Oct 21 '22 08:10

anio