- 论坛徽章:
- 0
|
纠正一下楼主,确实是交换了,你的测试程序里最后j还是等于2,是因为xchg()函数调用传递的是j的副本(值传递)。在xchg()函数返回之前,其2个形参确有交换。
参考代码:------------------------------------------------------------------------
#include <stdio.h>
struct __xchg_dummy { unsigned long a[100]; };
#define __xg(x) ((struct __xchg_dummy *)(x))
static inline unsigned long __xchg(unsigned long x, volatile void * ptr, int size)
{
printf("j=%d, *ptr=%d\n", (int)x, *(int *)ptr); // add
switch (size) {
case 1:
__asm__ __volatile__("xchgb %b0,%1"
:"=q" (x)
:"m" (*__xg(ptr)), "0" (x)
:"memory");
break;
case 2:
__asm__ __volatile__("xchgw %w0,%1"
:"=r" (x)
:"m" (*__xg(ptr)), "0" (x)
:"memory");
break;
case 4:
__asm__ __volatile__("xchgl %0,%1"
:"=r" (x)
:"m" (*__xg(ptr)), "0" (x)
:"memory");
break;
}
printf("j=%d, *ptr=%d\n", (int)x, *(int *)ptr); // add
return x;
}
#define xchg(ptr,v) ((__typeof__(*(ptr)))__xchg((unsigned long)(v),(ptr),sizeof(*(ptr))))
int main(int argc, char** argv)
{
int i = 1,j = 2;
printf("i=%d, j=%d\n", i, j);
printf("xchg:%d\n", xchg(&i, j));
printf("i=%d, j=%d\n", i, j);
return 0;
}
运行结果:
i=1, j=2
j=2, *ptr=1
j=1, *ptr=2
xchg:1
i=2, j=2 |
|