【发布时间】:2017-02-06 04:39:07
【问题描述】:
在下面的代码中,为什么交换函数以两种方式工作,将值传递为 swap(x,y) 和 swap(&x, &y)。
int main(){
int x, y;
cout << "Enter the values of x and y: ";
cin >> x >> y;
swap(x, y);
cout << "\nSwapped values are, x: " << x << " & y: " << y <<"\n";
return 0;
}
void swap(int *a, int *b){
int s;
s = *a;
*a = *b;
*b = s;
}
【问题讨论】:
-
避免使用
using namespace std;语句,您就不会遇到这些陷阱。 -
始终发布您的minimal reproducible example。你有
using namespace std,但没有在这里显示。忽略包含关键细节会浪费我们的时间!! -
请在您的
using namespace std和#includes 中编辑。 -
你的函数应该被称为 ::swap(&ax, &y)。
-
::swap(&x, &y) 当然...
标签: c++ pointers parameter-passing