Search code examples
c++optimizationprogram-entry-pointnoreturn

Does adding [[noreturn]] to main function make sense


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;
}

Solution

  • 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.