十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

【2015-01-18】GCC扩展关键字typeof学习笔记

【2015-01-18】GCC扩展关键字typeof学习笔记 [历史归档]本文原发布于 cstriker1407.info 个人博客内容为历史存档仅供参考。发布时间2015-01-18 标题GCC扩展关键字typeof学习笔记分类编程 / C C 标签gcc·typeofGCC扩展关键字typeof学习笔记官方的介绍网址参考文档:官方的介绍网址【 https://gcc.gnu.org/onlinedocs/gcc/Typeof.html#Typeof 】参考文档:【 http://blog.csdn.net/npy_lp/article/details/6989676 】【 http://blog.chinaunix.net/uid-28458801-id-4200573.html 】以下内容来自【 http://blog.csdn.net/npy_lp/article/details/6989676 】有删改关键字typeof用于获取表达式的数据类型。简单例子如清单1char*chptr01;typeof(*chptr01)ch;//等价于char ch;typeof(ch)*chptr02;//等价于char *chptr02;typeof(chptr01)chparray[5];//等价于char *chparray[5];例子中chptr01的数据类型为char **chptr01的数据类型为char。复杂的例子如清单2:#includestdio.h#definearray(type,size)typeof(type)intfunc(intnum){returnnum5;}intmain(void){typeof(func)*pfuncfunc;//等价于int (*pfunc)(int) func;printf(pfunc(10)%d ,(*pfunc)(10));array(char,)charrayhello world!;//等价于char charray[] hello world!;typeof(char*)charptrcharray;//等价于char *charptr charray;printf(%s ,charptr);return0;}在Linux内核中的应用如清单3/* linux-2.6.38.8/include/linux/kernel.h */#definemin(x,y)({\typeof(x)_min1(x);\typeof(y)_min2(y);\(void)(_min1_min2);\_min1_min2?_min1:_min2;})#definemax(x,y)({\typeof(x)_max1(x);\typeof(y)_max2(y);\(void)(_max1_max2);\_max1_max2?_max1:_max2;})通过typeof获得x和y的数据类型然后定义两个临时变量并把x和y的值分别赋给这两个临时变量最后进行比较。另外宏定义中(void)(_min1 _min2)语句的作用是用来警告x和y不能属于不同的数据类型。以下内容来自【 http://blog.chinaunix.net/uid-28458801-id-4200573.html 】有删改一说明typeof的参数可以是两种形式表达式或类型。1表达式的的例子如果将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];4typeof(int \*) p1,p2; /\* Declares two int pointers p1, p2 \*/ int \*p1, \*p2; 5typeof(int) \*p3,p4;/\* Declares int pointer p3 and int p4 \*/ int \*p3, p4; 6typeof(int [10]) a1, a2;/\* Declares two arrays of integers \*/ int a1[10], a2[10];三局限typeof构造中的类型名不能包含存储类说明符如extern或static。不过允许包含类型限定符如const或volatile。例如下列代码是无效的因为它在typeof构造中声明了externtypeof(extern int) a;
返回列表