`void` versus `[[noreturn]]` – Arthur O'Dwyer – Stuff mostly about C++

submited by
Style Pass
2022-07-02 05:30:09

All compiler vendors agree that divide2 should produce a warning along the lines of “control reaches end of non-void function,” but divide1 is totally fine. Our newbie was confused by this behavior. In the case of divide1, we return a value in the if branch but not in the else branch; the compiler is fine with this, because it knows throw means “this branch doesn’t return anything; it throws.” In divide2 we do the same thing, but just hidden inside the throw_error helper function. Suddenly the compiler is not okay with this.

An expert advised to mark throw_error with the [[noreturn]] attribute, to show the compiler that throw_error really never returns and therefore it can be treated the same as a throw. Our newbie replied:

I don’t understand why that should change things. throw_error’s return type being void already means it never returns anything.

This reminded me of the classic exchange from Act III of Tom Stoppard’s Rosencrantz and Guildenstern Are Dead (see also the scene from the 1990 movie version).

Leave a Comment