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

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.

Or maybe its come from gcc with compilation flags ?

Do you know how your project is compiled ?

Remi99
Associate II

For more information, here is the SonarQube rules : 

Remi99_0-1708964189860.png

Remi99_2-1708964267704.png

 

 

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.

To give better visibility on the answered topics, please click on "Accept as Solution" on the reply which solved your issue or answered your question.

is gcc is your compiler ?

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.

Remi99
Associate II

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.

Pavel A.
Evangelist III

Since C99, int main() does NOT have to return anything. Now you can understand why they made this improvement ))

Here, its not about code quality, but about follow the norms of your compiler.