Does it make sense to add [[noreturn]] to the main function

As far as I understand, the C ++ attribute [[noreturn]]

can be applied to functions that do not return to the caller so that the compiler can generate more optimized code. I understand that this matters for "regular" functions, but was wondering if this would have a performance impact when applied to a function main

.

Assuming I want to continually write a program without being able to interrupt it (which means the function main

will never return to the caller (= operating system)

Which one generates faster (more optimized) code or doesn't matter at all?

Option 1:

int main()
{
    while(true)
    //..
    return 0;
}

      

Option 2:

[[noreturn]] int main()
{
    while(true)
    //..
    return 0;
}

      

+3


source to share


2 answers


noreturn

mostly useful for callers, not the functions themselves, and in the case the main()

caller main()

is the C ++ runtime that's ready, so the compiler doesn't get to get to compile it, so there's nothing optimized in there.

Yours main()

has a tiny advantage, however, as in theory the version noreturn

will produce slightly less code as the compiler might omit the sequence of instructions known as the epilogue.



These performance (speed / size) metrics are trivial and don't deserve much attention. More interesting is the possibility of getting a warning if you wrote the code immediately after calling the function noreturn

. In this case, the compiler should be able to warn you that this code of yours will never be executed. I find it more useful.

+3


source


The noreturn attribute should be used for functions that are not returned to the caller. This is not to say that functions are void (which return to the caller - they just don't return a value), but functions in which the flow of control does not return to the calling function after the function has completed (like functions exiting the application, loop forever, or throw exception) ...

This can be used by compilers to make some optimizations and generate more efficient warnings. For example, if f has the noreturn attribute, the compiler may warn you that g () is dead code when writing f (); r () ;. Likewise, the compiler will know not to warn you about missing return statements after calls to f ().

from What is the meaning of noreturn?



EDIT:

to answer this post clearly. There is, I think, a tiny benefit to not using return in the main, but this is bad practice. In C / C ++ the "convention" if everything works well, you should return 0;

in your main

+1


source







All Articles