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

时光怂恿深爱的人放手 提交于 2019-12-11 03:43:30

问题


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?


回答1:


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




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/14652159/if-a-function-never-returns-is-it-valid-to-omit-a-return-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!