简体   繁体   English

RETURN语句中的表达式将被执行吗?

[英]Expression in RETURN statement will be executed?

I have a problem,will expressions in RETURN statement be excuted? 我有问题,RETURN语句中的表达式会被排除吗?

int test()
{
    top=10;
    return top--;
}

My problem is,what's the value of top ,10 or 9? 我的问题是, top ,10或9的值是多少? Anybody can help me?I'm just a beginner. 有人可以帮助我吗?我只是一个初学者。

The return value of test() in this case will be 10; 在这种情况下,test()的返回值为10; The decrement on the 'top' variable will occur after the function's return value has been returned. 在返回函数的返回值之后,将在“ top”变量上进行递减。

So say you have top as a global 因此,说您在全球范围内名列前茅

int top;

int test()
{
    top = 10;
    return top--;
}

int main()
{
    top = 0;

    int tmp = test();

    std::cout << "top " << top << " tmp " << tmp << std::endl; // top = 9, tmp = 10
    return 0;
}

The postfix increment and decrement operators will always be performed after the current value is used, so in the code shown in the question 10 will be returned. 使用当前值后,将始终执行后缀递增和递减运算符,因此将返回问题10所示的代码。 What the value of top is in the function afterwards doesn't matter, since the function will no longer be executing. 之后函数中top的值无关紧要,因为该函数将不再执行。 If the compiler is smart enough, it might optimize away the actual decrement since it's "dead code". 如果编译器足够聪明,它可能会优化掉实际的递减量,因为它是“死代码”。

top-- will decrement top and return the original, so test will return 10 . top--将减小top并返回原始值,因此test将返回10 If top has local storage duration, theoretically it will have a value of 9 when the function returns, but that doesn't really mean anything as the function is over and the whole calculation will likely be optimized out anyway. 如果top具有本地存储持续时间,则从理论上讲,函数返回时它将具有9的值,但这实际上并不意味着函数结束,并且无论如何总的计算都可能会得到优化。 If top has non-local storage then you can rely on it being 9 when the function exits. 如果top具有非本地存储,那么您可以在函数退出时依靠它为9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM