# 小朋友学C++（14）：两数交换

```#include <iostream>
using namespace std;
void swap(int m, int n)
{
cout << "Memory address of m: " << &m << endl;
cout << "Memory address of n: " << &n << endl;
cout << "\nBefore Swap:" << endl;
cout << "m = " << m << endl;
cout << "n = " << n << endl;
m ^= n;
n ^= m;
m ^= n;
cout << "\nAfter Swap:" << endl;
cout << "m = " << m << endl;
cout << "n = " << n << endl;
}
int main(int argc, char** argv)
{
int a = 1;
int b = 2;
cout << "Memory address of a: " << &a << endl;
cout << "Memory address of b: " << &b << endl;
swap(a, b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}```

```Memory address of a: 0x7fff90371cd8
Memory address of b: 0x7fff90371cdc
Memory address of m: 0x7fff90371c9c
Memory address of n: 0x7fff90371c98
Before Swap:
m = 1
n = 2
After Swap:
m = 2
n = 1
a = 1
b = 2```

```#include <iostream>
using namespace std;
void swap(int &m, int &n)
{
cout << "Memory address of m: " << &m << endl;
cout << "Memory address of n: " << &n << endl;
cout << "\nBefore Swap:" << endl;
cout << "m = " << m << endl;
cout << "n = " << n << endl;
m ^= n;
n ^= m;
m ^= n;
cout << "\nAfter Swap:" << endl;
cout << "m = " << m << endl;
cout << "n = " << n << endl;
}
int main(int argc, char** argv)
{
int a = 1;
int b = 2;
cout << "Memory address of a: " << &a << endl;
cout << "Memory address of b: " << &b << endl;
swap(a, b);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
}```

```Memory address of a: 0x7fffd009de98
Memory address of b: 0x7fffd009de9c
Memory address of m: 0x7fffd009de98
Memory address of n: 0x7fffd009de9c
Before Swap:
m = 1
n = 2
After Swap:
m = 2
n = 1
a = 2
b = 1```

239 篇文章44 人订阅

0 条评论

## 相关文章

1273

### SpringBoot 中异常处理

SpringBoot 中异常处理非常简单，通过@ControllerAdvice 和@ExceptionHandler 注解，可以实现自定义的统一异常处理模块。

4654

1783

4513

2529

### Scalaz（50）－ scalaz-stream: 安全的无穷运算－running infinite stream freely

scalaz-stream支持无穷数据流（infinite stream），这本身是它强大的功能之一，试想有多少系统需要通过无穷运算才能得以实现。这是因为外界...

1946

### Scalaz（47）－ scalaz-stream: 深入了解-Source

scalaz-stream库的主要设计目标是实现函数式的I/O编程（functional I/O）。这样用户就能使用功能单一的基础I/O函数组合成为功能完...

2805

53310

### Scalaz（46）－ scalaz-stream 基础介绍

scalaz-stream是一个泛函数据流配件库（functional stream combinator library），特别适用于函数式编程。sc...

2137

2785