2024-02-26 08:08 AM - edited 2024-02-26 08:11 AM
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.
2024-02-26 09:58 AM
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?
2024-02-26 10:08 AM
> 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.
2024-02-26 10:24 AM - edited 2024-02-26 10:26 AM
> 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.
2024-02-26 02:15 PM
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...