随便胡胡,交个作业的话,可以用gcc扩展typeof
程序代码:
#include <stdio.h>
#define SWAP(a,b) do{ __typeof(a) t=(a); (a)=(b); (b)=t; } while(0)
int main(void)
{
int a=1, b=2;
SWAP( a, b );
printf( "a=%d,b=%d\n", a, b );
return 0;
}
如果正式一些的话,得这么写
程序代码:
#include <stdio.h>
#include <string.h>
void swap_iterator( void *left, void *right, size_t len )
{
char tmp[len];
memcpy( tmp, left, len );
memcpy( left, right, len );
memcpy( right, tmp, len );
}
#define SWAP(a,b) swap_iterator(&a,&b,sizeof(a))
int main(void)
{
int a=1, b=2;
SWAP( a, b );
printf( "a=%d,b=%d\n", a, b );
return 0;
}