缺少返回值的函数,运行时的行为 [英] Function with missing return value, behavior at runtime

查看:135
本文介绍了缺少返回值的函数,运行时的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如预期,编译器(VisualStudio 2008)会发出警告

As expected, the compiler (VisualStudio 2008) will give a warning


警告C4715:'doSomethingWith':not
所有控制路径在编译以下代码时都会返回值

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。

But the program runs just fine. The return value of function doSomethingWith() is 0.

Is只是未定义的行为,或者是否有一定的规则在运行时如何创建/计算结果值。非POD数据类型作为返回值会发生什么?

Is is just undefined behavior, or is there a certain rule how the result value is created/computed at runtime. What happens with non-POD datatypes as return value?

推荐答案

它是ISO C ++标准第6.6节中规定的未定义行为。 3:

It is Undefined behaviour as specified in the ISO C++ standard section 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.

这篇关于缺少返回值的函数,运行时的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆