c语言:13.8、交换变量例子
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void SwapInt(int *left, int *right){
int temp = *left;
*left = *right;
*right = temp;
}
void Swap(void *left, void *right, size_t size){
void *temp = malloc(size);
if(temp){
memcpy(temp, left, size);
memcpy(left, right, size);
memcpy(right, temp, size);
free(temp);
}else{
}
}
#define SWAP(a, b, type) do{type temp = a; a = b; b = temp;}while(0)
#define SWAP_EXT(a, b) do{typeof(a) temp = a; a = b; b = temp;}while(0)
int main(){
int a = 1,b=2;
SwapInt(&a, &b);
printf("%d,", a);
printf("%d\n", b);
double x = 3.0;
double y = 4.0;
Swap(&x,&y, sizeof(double ));
printf("%f,", x);
printf("%f\n", y);
SWAP(x, y, double);
printf("%f,", x);
printf("%f\n", y);
SWAP_EXT(x, y);
printf("%f,", x);
printf("%f\n", y);
return 0;
}