Why there is no compiler error when return statement is not present?

前端 未结 7 1360
自闭症患者
自闭症患者 2021-01-08 00:19

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

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

This oft

7条回答
  •  渐次进展
    2021-01-08 00:44

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

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

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

    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 is smart enough to emit a diagnostic on my machine.

提交回复
热议问题