20

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 ?

4

3 回答 3

24

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.

于 2012-12-03T20:48:54.437 回答
6

__attribute__((noreturn)) or _Noreturn is useful for functions like die():

static __attribute__((noreturn)) void die(const char *fmt, ...) {
     /* print a formatted error message and exit  */
     exit(EXIT_FAILURE);
}
/* And let's say in main() you would want to exit because of an error but unforunately GCC complains about return value.  */
int main() 
{
    if (!whatever)
         die("a nasty error message goes here\n");
}

And is also used for optimizations as stated.

于 2012-12-03T21:31:10.763 回答
0

It allows additional optimizations to be made by the compiler. Take a look here at GCC's noreturn attribute which it supports for a while now (semantics is probably the same)

于 2012-12-03T20:49:55.293 回答