我无法理解一件奇怪的事情。这是我的程序:
#include <iostream>
using namespace std;
void Swap(int *a , int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int a=0;
int b=0;
cout<<"Please enter integer A: ";
cin>>a;
cout<<"Please enter integer B: ";
cin>>b;
cout<<endl;
cout<<"************Before Swap************\n";
cout<<"Value of A ="<<a<<endl;
cout<<"Value of B ="<<b<<endl;
Swap (&a , &b);
cout<<endl;
cout<<"************After Swap*************\n";
cout<<"Value of A ="<<a<<endl;
cout<<"Value of B ="<<b<<endl;
return 0;
}
现在,如果您查看函数“Swap”,我使用的是“void Swap”。因此它不能向主函数返回任何值(只有“int”返回一个值(至少我的老师是这么教我的))。但是如果你执行它,值会在 main 函数中交换!怎么会 ?谁能告诉我这怎么可能?
最佳答案
示例中的交换函数只是交换两个整数,但不返回任何内容。
为了检查哪个函数已经重新调整,你必须将它分配给一些变量,就像这样
int a = swap(&a, &b);
但是这段代码有错误,因为交换函数没有返回任何东西。
另一个例子:
int func() {
return 18;
}
int main() {
int a = func();
cout << a;
}
没问题,因为变量 a 是 int 并且函数 func 返回一个 int。
关于c++ - 为什么 void 返回一个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20030790/