1

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.

DonBaka
  • 325
  • 2
  • 14
  • 5
    If you are never going to return something, why do you declare the function as doing so? Just make it return `void` if you are not going to return anything. The compiler is trying to help you out with this by issuing a warning/error. – NathanOliver Oct 13 '21 at 13:23
  • 2
    @NathanOliver One could imagine a slightly more complex example which was fully reasonable, like `int div_checked(a, b) { if(b) return a/b; else log_error_and_die(); }`. – Sneftel Oct 13 '21 at 13:31
  • @Sneftel Good point. I forgot it would still issue if all paths don't have a return. – NathanOliver Oct 13 '21 at 13:35

1 Answers1

5

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]].

Sneftel
  • 40,271
  • 12
  • 71
  • 104