Home > Software engineering >  no return statement in function returning non-void while using C
no return statement in function returning non-void while using C

Time:10-14

I am trying to understand the C (GCC compiler) expectation of return statement in a non-void function.

For example, running this piece of code is working fine:

int foo() 
{ 
    throw "blah";
}

While, on the other hand, if we try to use/call some function to complete the throw, it is facing the well known error/warning of:

no return statement in function returning non-void 

for example:

void throw_blah() 
{
    throw "blah";
}

int foo() 
{ 
    throw_blah();
}

I am pretty curious about this as this is directly related to one of my other issue, where just like here, throw is working fine but using macro for throw is facing the same error.

CodePudding user response:

The compiler isn't going to go to very much trouble to detect this situation, because functions like throw_blah which are guaranteed to never return are rare, and because except in the simplest of situations, there's no way for it to reliably do so. If you have a function like throw_blah which is defined to never return, you can use the [[noreturn]] attribute to tell the compiler about it, and it will suppress the warning.

Note that throw_blah is the weird bit, not foo. If you called exit instead of throw_blah from foo, for instance, it wouldn't issue the error. That's because exit is marked as [[noreturn]].

  • Related