Use of _Noreturn in C11

c c11
user1255770 picture user1255770 · Dec 3, 2012 · Viewed 7.4k times · Source

Possible Duplicate:
What is the point of the Noreturn attribute?

C11 introduced the _Noreturn attribute to indicate that a function never returns.

Except for documentation value in the source code, what other benefits do the attribute provide, and why would one use it ?

Answer

Matteo Italia picture Matteo Italia · Dec 3, 2012

If a function calls unconditionally a _Noreturn function, the compiler will be able to understand that:

  • the code that follows is dead code, which allows for optimization (it can be removed from the generated binary) and diagnostics - the compiler will be able to emit a "non-reachable code" warnings;

  • most importantly, knowing that the normal flow from the function is interrupted it will be able to avoid spurious warnings about missing return values, uninitialized variables and the like.

    This is particularly important with static code analyzers - the number of false positives given by CLang static analyzer in a biggish application of ours dropped considerably once we marked our die function (log a fatal error and terminate the application) as noreturn.

There may be also some other optimization available - since the function never returns, there's no need to push the return address on the stack, save the state of the registers and whatever, all that's needed is to pass the arguments and do a jmp to the start of the function, without worrying about the return and the post-return cleanup. But of course, since the call is one-shot, the performance to squeeze here is mostly negligible.