Suppress a non-trivially useless warning "control might reach the end of a non-void function"

This is more of a convenience issue than anything, but I would like to know if there is a way to suppress the warning:

may reach end of non-void function [-Wreturn-type]

for specific cases where I know there are no problems with the code. I have some helper functions in my codebase for throwing exceptions and for code like this:

int foo(int i) {
    if (i > 10) {
        return i*10;
    }
    else {
        Exception::throwExcept(MyCustomException("Error: i not in the accepted range"));
    }
}

      

I know that he will either return or quit, no matter what. So the warning is pretty useless in my eyes, it's just that the compiler can't figure out that the control flow path is actually being thrown.

I would still like to see this pop-up warning for cases where it is actually a sign of bad code (i.e., with a path that does not return or throw).

Is this possible in portable mode?

EDIT: Forgot to add the compiler I'm using,

Apple LLVM version 8.1.0 (clang-802.0.41)

+3


source to share


4 answers


The compiler can't figure out what Exception::throwExcept()

won't return. There are two solutions here. One of them is to tell the compiler that, i.e.

struct Exception
{
    [[noreturn]] static void throwExcept(SomeType const&);
};

      



(clang -Wmissing-noreturn

, which is incorporated -Weverything

, will alert if the above function can be declared [[noreturn]]

, but not) or a function as a reorder

int foo(int i) {
    if (!(i>10))
        Exception::throwExcept(MyCustomException("Error: i not in the accepted range"));

    return i*10;
}

      

+10


source


The function label Exception::throwExcept

[[noreturn]]

should help the compiler figure out that it, in fact, will not be returned.



+7


source


A quick and dirty way to suppress an error is to use the comma operator in the return statement. If you are using

return Exception::throwExcept(MyCustomException("Error: i not in the accepted range")), 0;

      

The compiler will see a return statement, but it will never execute as

Exception::throwExcept(MyCustomException("Error: i not in the accepted range"))

      

Throws before he can return 0.

+2


source


It seems to me that your compiler cannot see inside Exception::throwExcept

to know that it will always throw an exception.

Help the compiler with the original C ++ exception throw

as the last line of your function: throw std::exception("Just to help the compiler know to not warn here");

This will not hurt performance from the moment the code is executed and will never execute.

+1


source







All Articles