代码如下:
-
#define ConvertMem2Var1(ret,mem) ({ \
-
if(1 != sizeof(mem))return 0; \
-
typeof(&ret) _p = (mem); *_p;})
-
-
#define ConvertMem2Var2(ret,pt) ({ \
-
ASSERT(sizeof(*pt) == 1); \
-
typeof(&ret) _p = (pt); \
-
switch(sizeof(*_p)/sizeof(pt[0])) \
-
{ \
-
case 1: pt++;break; \
-
case 2: pt+=2;break; \
-
} \
-
*_p; \
-
})
-
-
#define ConvertMem2Var3(ret,pt) ({ \
-
ASSERT(sizeof(*pt) == 1); \
-
typeof(&ret) _p = (pt); \
-
pt += sizeof(*_p)/sizeof(pt[0]); \
-
*_p; \
-
})
-
-
-
int test()
-
{
-
short int i;
-
long int l;
-
char *pm, mem[4] = {.....}, mem2[100];
-
pm = mem2;
-
i = ConvertMem2Var1(i, mem);
-
i = ConvertMem2Var2(i, pm); //执行后pm会自动按sizeof(i)递增
-
l = ConvertMem2Var2(l, pm);
-
l = ConvertMem2Var3(l, pm);
-
}
使用这种宏,让代码简洁明了。这样就不用写N个
ConvertMem2Var函数了。而且一个赋值语就可以执行一系列很复杂的操作,可以在宏内做各种错误检查(如数值范围检查),编程时,只需要想着给哪个变量赋什么值,而不用考虑是否会出错。虽然inline的函数也可以实现类似的功能,但函数对中变量的必须是固定的类型,还可能不好优化。如:
-
int ConvertMem2Var2(char *mem, int len)
-
{
-
int *_p = (int*)mem;
-
switch(len)
-
{
-
case 1: _p++;
-
case 2: _p += 2;
-
}
-
return _p;
-
}
其它的一些宏:
点击(此处)折叠或打开
-
#define max(a,b) ((a) > (b) ? (a) : (b))
-
-
#define maxint(a,b) \
-
({int _a = (a), _b = (b); _a > _b ? _a : _b; })
-
-
#define GetReturn(a) ({__typeof__(a) b = (a); b + 3; })
-
#define GetReturn(a) ({typeof(a) b = (a); b + 3; })
-
#define macro(array) typeof (*(array)) *_SEARCH_array = (array);
-
#define GetReturn(a) ({do{ \
-
typeof(a) *pa = &a; \
-
while(*pa){ \
-
a++; \
-
if((*pa % 4) == 3) goto Return; \
-
a+=2; \
-
if((*pa / 3) == 4) goto Return; \
-
a+=3; \
-
} \
-
Return: \
-
a; \
-
})
-
-
int i;
-
short si = 1234;
-
i = max(si, 2);
-
i = maxint(si, 2);
-
i = GetReturn(si);
阅读(1847) | 评论(0) | 转发(0) |