#include<stdio.h> #include<stdlib.h> int main() { int a = 1; int b = 2; int tmp = a; a = b; b = tmp; printf("a = %d b = %d\n",a,b); system("pause"); return 0; }
上面是用创建中间变量的方法交换,下面是不创建中间变量的另一种方法:
a = a+b; b = a-b; a = a-b; 当然还可以用异或: a = a^b; b = a^b; a = a^b; 以上都是在main函数中实现,下面一种方法创建了函数,用指针来交换两个整型值: #include<stdio.h> #include<stdlib.h> void Swap(int *p1, int *p2) { int tmp = *p1; *p1 = *p2; *p2 = tmp; } int main() { int a = 1; int b = 2; Swap(&a, &b); printf("a = %d b = %d\n",a,b); system("pause"); return 0; } 然而如果Swap函数写成下面这样是错误的,只是进行了值传递,上面的方法传的是地址 void Swap(int num1, int num2) { int tmp = num1; num1 = num2; num2 = tmp; }