cancel
Showing results for 
Search instead for 
Did you mean: 

Should main return 0 when there is a while(1) ?

Remi99
Associate II

Hi all,

I'm programming an embedded software.

According to C standards, I write : 

 

 

int main(void)
{
    // Init
    initMethod();

    /* Main loop */
    while (1)
    {
        execute();
    }

    // This return is never reached
    return 0;
}

 

 


But when my code is analyzed by SonarQube, I have a bug report: 'return' will never be executed.

To fix it, I would write the following:

 

 

int main(void)
{
    // Init
    initMethod();

    /* Main loop */
    while (1)
    {
        execute();
    }
}

 

 

But I'm annoyed with the fact that the main method doesn't have the "good" return type.
What is the good pratice in this case ?

Best regards.

13 REPLIES 13

The bigger question is WHERE it would return too? Not even sure the GNU startup would get you to exit()

Can you define it as not returning a value, and likely never leaving?

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
Pavel A.
Evangelist III

Not even sure the GNU startup would get you to exit()

At least there's the return instruction. In standalone environment aka "bare metal"  exit() is not warranted.

https://github.com/STMicroelectronics/cmsis_device_f4/blob/2e1724e592931693ce4dfc43e2fd6b3bc375d6a0/Source/Templates/gcc/startup_stm32f401xc.s#L101

 

Pavel A.
Evangelist III

But I'm annoyed with the fact that the main method doesn't have the "good" return type.

Int is the perfect return type for main(). The good practice? Before taking on a project, verify which language version and coding guidelines should be used. Refresh your C. Read documentation. Repeat every so often.

 

C came out of UNIX. The model for UNIX C programs is that it takes two parameters, argc and argv. argc is the count of parameters that were given on the shell command line, and argv is a vector of text strings containing all of the parameters from the command line. The program returns an integer that the shell uses as a return code indicating if the program ran and terminated properly (0) or improperly (something else).

Does any of this make sense in an embedded environment? Maybe.

It depends on who wrote the startup and shutdown code.

Your program is expected to never exit, but what if it does? I have seen instances where the shutdown code looks at the return code and will either restart your code or go into an infinite loop so that your machine fails fast.

For me, if lint complains that main should return an int, I'd return -1 since my program isn't supposed to terminate but did. If it gets caught by the shutdown code, hurray, I should have looked that up to see what will happen.

I've always wanted to write a system that starts up, does one swipe at a reading and control, then goes into a tight loop until it gets caught by the watchdog causing it to start up, do one swipe...