Search code examples
cgccavr

avr-gcc never returning main optimalization


Somewhere I read that if I never return from main() loop, I can spare ~66 Bytes with some compiler switch in avr-gcc, but I couldn't find the site anymore.

This is for embedded:

main() {
 while(1)
 {
   // do stuff
 }
}

Solution

  • For gcc you can use a special attribute to indicate that your function does not return:

    int main() __attribute__ ((noreturn)) {
        for (;;) {
             // do stuff
        }
        __builtin_unreachable ();
    }
    

    Optionally you can add __builtin_unreachable (); to indicate that some part of the code can never be reached.

    Although in most cases properly recognised by optimisation flags, without such while(1) can generate more code than for(;;).