2

Example:

int foo() { throw 0; }
int bar() { foo(); }

foo here doesn't get a warning, while bar gets the error "must return a value". More typically, bar would have some return statements and get the warning "not all control paths return a value".

Why isn't an indirect throw recognized as a proper way to exit the function? How can I work around it, ideally by modifying foo and not bar?

The actual example I have in mind is that I have a ThreadSafeExit function which calls the test platform's Exit function, and I hoped that adding throw 0 at the end would get rid of warnings.

1

1 Answer 1

11

You should be able to quiet the compiler by applying the noreturn attribute to foo.

[[noreturn]]int foo() { throw 0; }
int bar() { foo(); }

However in this case, I would really fix it this way:

int foo() { throw 0; }
int bar() { return foo(); }

This will also make the compiler happy and is a lot more natural to read, since it is very common to invoke another function to calculate your return value. The first way can leave someone scratching their head as to what is going on if foo and bar are not close to each other in code.

You can do both, of course to be super clear about the intent.

Sign up to request clarification or add additional context in comments.

6 Comments

How ever you go , I strongly recommend placing the return statement as the compiler isn't the only thing that will read the code. People will expect to see a return there, and there are few things more dangerous to code than a confused programmer.
@user4581301 The second option with return foo(); solves both silencing the warning and any user confusion that may arise I think.
@Ted my point is if there are two potential fixes, go with the one that doesn't <expletive deleted> with people's heads.
@user4581301 :-) That sounds like good advice. Going with both the attribute and the return would probably be the clearest and it may give the compiler the possibility to do some optimizations if the content of foo isn't seen in in bar's TU.
I think a return statement in bar is essential. Suppose someone makes a change to foo.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.