如预期的那样,编译器(VisualStudio 2008)将发出警告
warning C4715: ‘doSomethingWith’ : not
all control paths return a value
编译以下代码时:
int doSomethingWith(int value) { int returnValue = 3; bool condition = false; if(condition) // returnValue += value; // DOH return returnValue; } int main(int argc,char* argv[]) { int foo = 10; int result = doSomethingWith(foo); return 0; }
但程序运行正常.函数doSomethingWith()的返回值为0.
是只是未定义的行为,还是有一定的规则如何在运行时创建/计算结果值.非POD数据类型作为返回值会发生什么?
解决方法
它是ISO C标准第6.6.3节中规定的未定义行为:
Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.