我不明白一个奇怪的问题。这是我的程序:
#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”会返回一个值(至少这是我的老师教我的))。但是如果你执行它,主函数的值却被交换了!怎么可能?有人能告诉我它是如何实现的吗?
Swap
语句中写了return temp;
(例如),那么就会返回一个值,而这在void函数中是不允许的。Swap函数所做的是通过指针修改传递给它的变量。这是完全可以的。 - johnvoid
不返回任何值,其他所有类型都会返回。 - MSalters