Home > other >  Why/When would/should you use __attribute__((noreturn))?
Why/When would/should you use __attribute__((noreturn))?

Time:01-13

As I understand, this attribute tells the compiler that a function does not return. What is the benefit of specifying this when a function has a void return?

How are these two functions different?

void foo(){}
__attribute__((noreturn)) void foo(){}

CodePudding user response:

It doesn't mean that the function doesn't return a value - it means that the function doesn't return at all. Calling the function gives a one way trip.

There's some limited use of this in hardware-related programming, where you don't want any function call overhead to be generated on the caller-side stack, since you aren't going to return there anyway.

For example when calling void main (void) from the CRT start-up code inside a microcontroller embedded system - these are systems which keep running until you plug the power and they will never return from main(). So if the compiler for such a system supports _Noreturn void main (void), then that creates less wasted stack space. Otherwise the CRT will just push x bytes on the stack which will remain there forever, as dead space.

It might also be useful for diagnostic purposes, such as when examining the behavior of compilers. As was done here, when demonstrating some major bugs in the clang compiler.

CodePudding user response:

There is no relation between the return type, and a "no-return" behavior of the function.

The void return type is merely telling that this function returns no value (in case it returns).

Some function do not ever return to the caller. For example some message processing infinite loops, the exit() function or the functions for replacing the current process (such as exec* family). The __attribute__((noreturn)) is hinting the compiler that it might consider certain optimization for this specific function which are valid for functions that do not return - such as optimizing the overhead of calling such a function (like saving context of the caller, return address and such).

  •  Tags:  
  • Related