简体   繁体   English

如果函数永远不会返回,则省略return语句是有效的

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

Consider a function foo() that might never exit: 考虑一个可能永远不会退出的函数foo()

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? 省略最终的return语句是否有效? Will it evoke undefined behavior if I leave out that final statement? 如果我遗漏最后的陈述,它会引起不确定的行为吗?

You can omit the last return statment which is after an indefinite loop. 您可以省略在无限循环之后的最后一个return语句。 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. 如果在那种情况下真的需要那个无限循环,那么之后的return语句就是死代码。 Removing that will not be undefinite behaviour. 删除它不会是不确定的行为。

即使它没有返回语句也返回,除非你使用返回值,否则没有UB。

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. 对于非void函数,完全没有return语句或并非所有路径都具有return语句是有效的。

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的返回值是未定义的行为。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM