c++引用交换a和b的值
时间: 2024-06-12 20:09:05 浏览: 89
在C语言中,可以使用引用(即指针)来交换两个变量的值。以下是几种常见的方法:
方法一:
```c
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int a = -2;
int b = 16;
swap(&a, &b);
printf("a=%d\n", a);
printf("b=%d\n", b);
return 0;
}
```
方法二:
```c
void swap(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main() {
int a = -2;
int b = 16;
swap(a, b);
printf("a=%d\n", a);
printf("b=%d\n", b);
return 0;
}
```
方法三:
```c
#include <iostream>
void swap(int& x, int& y) {
int t = x;
x = y;
y = t;
}
int main() {
int a = -2;
int b = 16;
std::cout << "Before:" << std::endl;
std::cout << "a=" << a << std::endl;
std::cout << "b=" << b << std::endl;
swap(a, b);
std::cout << "After:" << std::endl;
std::cout << "a=" << a << std::endl;
std::cout << "b=" << b << std::endl;
return 0;
}
```
阅读全文