As far as I understand, C++ attribute [[noreturn]]
can be applied to functions not returning to the caller so that the compiler can generate more optimised code. I do understand it makes a difference for "normal" functions, but was wondering if it also makes a difference in performance when applying it to the main
function.
Assuming I want to write a program constantly running with no chance it aborts (meaning the main
function will never return to the caller (= operating system)
Which of this generates in faster (more optimised) code or does it not make a difference at all?
Option 1:
int main()
{
while(true)
//..
return 0;
}
Option 2:
[[noreturn]] int main()
{
while(true)
//..
return 0;
}
The noreturn
is mostly useful for callers of functions, not for the functions themselves, and in the case of main()
the caller of main()
is the C++ runtime, which is ready-made, so the compiler does not get to compile it, so there is nothing to optimize there.
However, there is a tiny benefit to be gained within your main()
, since theoretically, the noreturn
version will produce slightly smaller code, since the compiler can omit the sequence of instructions known as epilogue.
These performance (speed/size) gains are trivial and not really worth paying much attention to. What is more interesting is the possibility of receiving a warning if you have written any code right after a call to a noreturn
function. In this case the compiler should be able to warn you that this code of yours will never be executed. I find this a lot more useful.
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 exception).
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().
from What is the point of noreturn?
EDIT:
to asnwer clearly to the post. There is I think a tiny benefit to use no return in main but it's a bad practice. In C/C++ by "convention" if everything worked well you must return 0;
in your main
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With