写一个c++程序分别用指针和引用作为函数参数实现交换两个整型变量的值
时间: 2024-02-18 22:01:33 浏览: 133
c语言指针变量作为函数参数传递
使用指针作为函数参数实现交换两个整型变量的值的程序如下:
```c++
#include <iostream>
using namespace std;
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
cout << "Before swap: x = " << x << ", y = " << y << endl;
swap(&x, &y);
cout << "After swap: x = " << x << ", y = " << y << endl;
return 0;
}
```
使用引用作为函数参数实现交换两个整型变量的值的程序如下:
```c++
#include <iostream>
using namespace std;
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 10, y = 20;
cout << "Before swap: x = " << x << ", y = " << y << endl;
swap(x, y);
cout << "After swap: x = " << x << ", y = " << y << endl;
return 0;
}
```
这两个程序的输出结果都应该为:
```
Before swap: x = 10, y = 20
After swap: x = 20, y = 10
```
阅读全文