下面的代码打印:
5
为什么打印 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;
}
最佳答案
您遇到了未定义的行为。你的函数实际上没有 return
任何事物!查看每个条件:
-
c>10
?是的。 -
a<b && a >0
?没有。 -
b<0
?没有。
所以你永远不会击中任何 return
秒。这意味着您的程序中绝对可能发生任何事情。在您的情况下,5
似乎恰好发生了。存储在程序需要 return
的位置值(value)。
关于c++ - If-else 语句中的返回值 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19737099/