If-else 语句中的返回值 - C++

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19737099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:06:21  来源:igfitidea点击:

Return value in If-else statement - C++

c++if-statementreturn-value

提问by user1559792

The below code prints:

下面的代码打印:

5

Why does it print 5? Also if it returns 5 why it doesn't print "James"? I do not understand the below code. If I delete the else word it prints -1. However shouldn't it return a default value?

为什么它打印5?另外,如果它返回 5 为什么它不打印“James”?我不明白下面的代码。如果我删除 else 单词,它会打印 -1。但是它不应该返回一个默认值吗?

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int fonk()
{
    int a = 5, b = 3;
    int c = a*b;
    if(c >10)
    {
        if( a<b && a >0)
        {   cout <<"James";
        return a;
        }

        else if(b<0)
        {
            return b;
        }

    }
    else return -1;

}

int main()
{
    int x = fonk();
    cout << x;
}

回答by BoBTFish

You are hitting undefined behaviour. Your function actually doesn't returnanything! Look at each condition:

您遇到了未定义的行为。你的功能实际上return什么都没有!查看每个条件:

  • c>10? yes.
  • a<b && a >0? no.
  • b<0? no.
  • c>10? 是的。
  • a<b && a >0? 不。
  • b<0? 不。

So you never hit any of the returns. This means absolutely anything could happen in your program. In your case, it seems to just so happen that 5is stored where the program expects a returnvalue.

所以你永远不会击中任何returns。这意味着您的程序中绝对可能发生任何事情。在您的情况下,似乎恰好5存储在程序return期望值的位置。

回答by kfsone

So the first two lines of fonk delcare the following values:

所以 fonk delcare 的前两行值如下:

int a = 5, b = 3, c = a *b;

So ais 5, bis 3 and cis 15.

所以a是5,b为3和c15。

if(c >10)

15 is greater than 10.

15 大于 10。

    if( a<b && a >0)

this is not true, so the James/return a branch is not executed.

事实并非如此,因此不会执行 James/return a 分支。

    else if(b<0)

b is 3, which is >= 0, so the return b statement is not executed.

b 为 3,即 >= 0,因此不执行 return b 语句。

else

this statement refers to "c > 10", the c > 10 was true, so this else clause is not executed.

该语句引用“c > 10”,c > 10 为真,因此不执行此 else 子句。

}

your function ends without returning anything, this invokes "Undefined Behavior".

您的函数结束而不返回任何内容,这将调用“未定义行为”。

Solutions: Remove the 'else' from else return -1;or add a return -2;to see the case where your code followed none of the paths.

解决方案:从中删除“else”else return -1;或添加一个return -2;以查看您的代码不遵循任何路径的情况。

I see you're using GCC -- add the '-Wall' option to get maximal diagnostics from the compiler, it should tell you that your function has a code path which does not return a value.

我看到您正在使用 GCC——添加“-Wall”选项以从编译器获得最大诊断,它应该告诉您您的函数具有不返回值的代码路径。

回答by villintehaspam

Nah, you've got it slightly wrong. Your last else belongs to the first if statement, so that will never be called. Your function happens to return 5 because that happens to be in the place where the compiler normally places the return value.

不,你弄错了。您的最后一个 else 属于第一个 if 语句,因此永远不会被调用。您的函数恰好返回 5,因为它恰好位于编译器通常放置返回值的位置。

You can't rely on that though as it is undefined behavior as per the C++ standard section 6.6.3 (if my google skills serve me right).

你不能依赖它,因为它是未定义的行为,根据 C++ 标准第 6.6.3 节(如果我的谷歌技能对我有用)。

回答by I?ya Bursov

this is offtopic for this site, but lets go through each line

这是本网站的题外话,但让我们看看每一行

int a=5, b =3;
int c = a*b;

c is 15 right now

c 现在是 15

if(c >10) // 15>10 - true
{
    if( (a<b) && (a>0) ) // 5<3 - false, so we go further
    {
        cout <<"James";
        return a;
    }
    else if(b<0) // 3<0 - false, we go further
    {
        return b;
    }
    // here is error, should be another one return
}
else
    return -1; // this will not be executed, as it is else for if (c>10)

update: why it returns 5 - usually return value of function is placed into (e)ax register (I assume you're on x86 platform), so your compiler used ax for storing value of a during comparison

更新:为什么它返回 5 - 通常函数的返回值放在 (e)ax 寄存器中(我假设你在 x86 平台上),所以你的编译器在比较期间使用 ax 来存储 a 的值

回答by Yakk - Adam Nevraumont

If you exit a function that returns intwithout returning a value, the result is undefined. Not a default value.

如果退出一个int没有returning 值就返回的函数,结果是未定义的。不是默认值。

The compiler could print 5, could print 0, coukd print 4232732, or it could format your hard drive. All woukd be legal C++ results of your program.

编译器可以打印 5,可以打印 0,coukd 可以打印 4232732,或者它可以格式化您的硬盘。所有这些都将是您程序的合法 C++ 结果。

The way to handle this is two fold: turn on warnings and warnings as errors, as there is most definitely a wsrning for not all control paths returning a value.

处理这个问题的方法有两种:打开警告和警告作为错误,因为并非所有返回值的控制路径肯定都有一个 wsrning。

Second, do not make functions where not all control paths return a value.

其次,不要创建并非所有控制路径都返回值的函数。