如果不用中间变量交换,你可以考虑用XOR Swap
#include <stdio.h>
/** Inplace swap using the XOR operation */
void xor_swap(int *a, int *b)
{
if (a != b)
{
*a ^= *b; // a = A XOR B
*b ^= *a; // b = B XOR ( A XOR B ) = A
*a ^= *b; // a = ( A XOR B ) XOR A = B
}
}
void xor_swapf(float *a, float *b)
{
xor_swap((int *)a, (int *)b);
}
int main()
{
int a = 1, b = 2;
float c = 1.23, d = 4.56;
printf("before:\n");
printf("a=%d b=%d\n", a, b);
printf("c=%f d=%f\n", c, d);
xor_swap(&a, &b);
xor_swapf(&c, &d);
printf("after:\n");
printf("a=%d b=%d\n", a, b);
printf("c=%f d=%f\n", c, d);
return 0;
}
$ gcc -Wall main.c
$ ./a.out
before:
a=1 b=2
c=1.230000 d=4.560000
after:
a=2 b=1
c=4.560000 d=1.230000