Skip to main content
Associate II
February 26, 2024
Question

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

  • February 26, 2024
  • 11 replies
  • 3485 views

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.

    11 replies

    Andrei Chichak
    Lead
    February 26, 2024

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