C语⾔中typeof()函数的⽤法
前⾔:
typeof关键字是C语⾔中的⼀个新扩展,这个特性在linux内核中应⽤⾮常⼴泛。
typeof的用法⼀,说明
typeof的参数可以是两种形式:表达式或类型。
1,表达式的的例⼦:
typeof(x[0](1)
这⾥假设x是⼀个函数指针数组,这样就可以得到这个函数返回值的类型了。
如果将typeof⽤于表达式,则该表达式不会执⾏。只会得到该表达式的类型。
以下⽰例声明了int类型的var变量,因为表达式foo()是int类型的。由于表达式不会被执⾏,所以不会调⽤foo函数。            extern int foo();
typeof(foo()) var;
2,参数的例⼦:
typeof(int *) a,b;
等价于:
int *a,*b;
⼆,实例
1,把y定义成x指向的数据类型:
typeof(*x) y;
2,把y定义成x指向数据类型的数组:
typeof(*x) y[4];
3,把y定义成⼀个字符指针数组:
typeof(typeof(char *)[4] y;
这与下⾯的定义等价:
char *y[4];
4,typeof(int *) p1,p2; /* Declares two int pointers p1, p2 */
int *p1, *p2;
5,typeof(int) *p3,p4;/* Declares int pointer p3 and int p4 */
int *p3, p4;
6,typeof(int [10]) a1, a2;/* Declares two arrays of integers */
int a1[10], a2[10];
7,定义⼀个宏返回⼀个最⼤值,为避免因为重复调⽤同⼀个变量,可以这样
把    MAX(x,y)  ((x)>(y)?(x):(y))
改成  MAX(x,y)  ({  typeof(x) _x=x;\
typeof(x) _y=y;\
_x>_y?_x:_y;\
})
三,局限
typeof构造中的类型名不能包含存储类说明符,如extern或static。不过允许包含类型限定符,如const或volatile。例如,下列代码是⽆效的,因为它在typeof构造中声明了extern:
typeof(extern int) a;
四,⽂件参考
1,blog.csdn/wslong/article/details/7728811
2,/onlinedocs/gcc/Typeof.html#Typeof

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。