当不存在return语句时,为什么没有编译器错误?

当不存在return语句时,为什么没有编译器错误?

问题描述:

与Java不同,在C/C ++中,允许:

Unlike Java, in C/C++ following is allowed:

int* foo ()
{
  if(x)
    return p;
// what if control reaches here
}

这通常会导致崩溃并难以调试问题.为什么 standard 对非 void 函数不强制具有最终回报?(编译器针对错误的 return 值生成错误)

This often causes crashes and hard to debug problems. Why standard doesn't enforce to have final return for non-void functions ? (Compilers generate error for wrong return value)

gcc/msvc中是否有任何标志可以强制执行此操作?(类似于 -Wunused-result )

Is there any flag in gcc/msvc to enforce this ? (something like -Wunused-result)

不允许(未定义行为).但是,在这种情况下,该标准不需要诊断.

It is not allowed (undefined behaviour). However, the standard does not require a diagnostic in this case.

由于这样的代码,该标准不需要最后一个语句为 return :

The standard doesn't require the last statement to be return because of code like this:

while (true) {
  if (condition) return 0;
}

这总是返回0,但是哑编译器看不到它.请注意,该标准未强制要求智能编译器.在 while 块之后的 return 语句将是一种浪费,愚蠢的编译器将无法对其进行优化.该标准不希望程序员仅为了满足愚蠢的编译器编写浪费的代码.

This always returns 0, but a dumb compiler cannot see it. Note that the standard does not mandate smart compilers. A return statement after the while block would be a waste which a dumb compiler would not be able to optimise out. The standard does not want to require the programmer to write waste code just to satisfy a dumb compiler.

g ++ -Wall足够聪明,可以在我的计算机上发出诊断信息.

g++ -Wall is smart enough to emit a diagnostic on my machine.