fuz
fuz

Reputation: 92976

If a function never returns is it valid to omit a return statement

Consider a function foo() that might never exit:

int foo(int n) {
    if(n != 0) return n;
    else for(;;); /* intentional infinite loop */

    return 0; /* (*) */
}

Is it valid C to omit the final return-statement? Will it evoke undefined behavior if I leave out that final statement?

Upvotes: 2

Views: 391

Answers (3)

ouah
ouah

Reputation: 145829

For a non-void function, it is valid to have no return statements at all or that not all the paths have a return statement.

For example:

// This is a valid function definition.
int foo(void)
{
}

or

// This is a valid function definition.
int bar(void)
{
    if (printf(""))
    {
        exit(1);
    }

    return 0;
}

but reading the return value of foo is undefined behavior.

foo();  // OK
int a = foo();  // Undefined behavior
int b = bar();  // OK

Upvotes: 1

rashok
rashok

Reputation: 13414

You can omit the last return statment which is after an indefinite loop. But you may be getting compilation warning like not all path are returning. Its not good to have an indefinite loop in a function. Keep one condition to break the loop.

If that indefinite loop is really required in that case anyway the return statement after that is a dead code. Removing that will not be undefinite behaviour.

Upvotes: 3

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

Even if it does return without a return statement there is no UB unless you use the return value.

Upvotes: 3

Related Questions