下面的代码打印:
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
期望值存储的位置。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句