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 08:12 AM
In C, the return statement should always match the return type. What you did is good and that warning is not so important. I dont know where it come from, because its not a warning-case of gcc. Maybe it come from another parser.
2024-02-26 08:13 AM
Or maybe its come from gcc with compilation flags ?
Do you know how your project is compiled ?
2024-02-26 08:17 AM
For more information, here is the SonarQube rules :
2024-02-26 08:25 AM
Hello,
Indeed in your case the return will never reached because of the while(1) loop. But, normally, it should be treated as a warning not an error.
2024-02-26 08:26 AM
is gcc is your compiler ?
2024-02-26 08:28 AM
There are severals "norms" about compiling C code around the world and epoch.
Yours seems to unaccept unreachable code. This is just a detail.
Later in your project, you will probably add some conditions to exit this while loop, and so you will have to add a return statement in your function.
2024-02-26 08:28 AM
I'm talking about quality. Not about compilation error.
The program compiles well and runs. But SonarQube (quality tool) return that the first code is not well written.
2024-02-26 09:36 AM - edited 2024-02-26 09:46 AM
Since C99, int main() does NOT have to return anything. Now you can understand why they made this improvement ))
2024-02-26 09:39 AM
Here, its not about code quality, but about follow the norms of your compiler.