当我运行这个程序时:
#include <iostream>
int sqr(int&);
int main()
{
int a=5;
std::cout<<"Square of (5) is: "<< sqr(a) <<std::endl;
std::cout<<"After pass, (a) is: "<< a <<std::endl;
return 0;
}
int sqr(int &x)
{
x= x*x;
}
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
Square of (5) is: 2280716
After pass, (a) is: 25
Run Code Online (Sandbox Code Playgroud)
什么是2280716?而且,如果函数中sqr(a)没有return语句,我如何获得返回的值int sqr(int &x)?
谢谢.
Fre*_*Foo 31
严格来说,这会导致未定义的行为.实际上,由于sqr具有返回类型int,即使没有return语句,它也总会返回一些内容.那东西可以是任何int价值.
添加return语句并在编译器中打开警告(g++ -Wall例如).
int sqr(int &x)
{
return x = x*x;
}
Run Code Online (Sandbox Code Playgroud)
这是一些垃圾,取决于一些因素.可能这是存储在内存中的值,如果它有一个return语句,函数会将结果放在内存中.该内存未经处理,然后由调用者读取.
不要想太多 - 只需添加一个return声明.
| 归档时间: |
|
| 查看次数: |
11749 次 |
| 最近记录: |