且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C和C ++函数没有return语句

更新时间:2022-05-30 08:35:16

这是为什么仍然被允许?实在不行,但一般来说,编译器不能的证明的你正在做它。考虑这个(当然极度简化)例如:

"Why is this still allowed?" It is not, but in general, the compiler cannot prove you are doing it. Consider this (of course extremely simplified) example:

// Input is always true because logic reason
int fun (bool b) {
    if (b)
        return 7;
}

甚至这一个:

int fun (bool b) {
    if (b)
        return 7;
    // Defined in a different translation unit, will always call exit()
    foo();
    // Now we can never get here, but the compiler cannot know
}

现在的第一个例子的的流动关闭端,但它绝不会只要功能用于正常;而第二个不能,但是编译器无法知道这一点。所以编译器将打破工作和法律,虽然可能愚蠢,code。通过使这个错误。

Now the first example could flow off the end, but it never will as long as the function is used "properly"; and the second one could not, but the compiler cannot know this. So the compiler would break "working" and legal, although probably stupid, code by making this an error.

现在您发布的例子有一点不同:这里的所有的路径流下结束,所以编译器可以拒绝或忽略这个功能。然而,它会破坏现实世界中code,它依赖于编译器的具体行为,在生产code和人不一样的是,即使他们是错的。

Now the example you posted is a little different: Here, all paths flow off the end, so the compiler could reject or just ignore this function. It would however break real world code that relies on the compiler specific behavior as in your production code, and people do not like that, even if they are wrong.

但最终,流下非月底 - 无效功能仍然是不确定的行为。它可能在某些编译器的工作,但它不是,从来没有被保证。

But in the end, flowing off the end of a non-void function still is undefined behavior. It might work on certain compilers, but it is not and never was guaranteed to.