What is the point of noreturn?

BЈовић picture BЈовић · May 10, 2012 · Viewed 33.9k times · Source

[dcl.attr.noreturn] provides the following example:

[[ noreturn ]] void f() {
    throw "error";
    // OK
}

but I do not understand what is the point of [[noreturn]], because the return type of the function is already void.

So, what is the point of the noreturn attribute? How is it supposed to be used?

Answer

sepp2k picture sepp2k · May 10, 2012

The noreturn attribute is supposed to be used for functions that don't return to the caller. That doesn't mean void functions (which do return to the caller - they just don't return a value), but functions where the control flow will not return to the calling function after the function finishes (e.g. functions that exit the application, loop forever or throw exceptions as in your example).

This can be used by compilers to make some optimizations and generate better warnings. For example if f has the noreturn attribute, the compiler could warn you about g() being dead code when you write f(); g();. Similarly the compiler will know not to warn you about missing return statements after calls to f().