C 语言中 typeof keyword简单介绍

原文:http://hi.baidu.com/leowang715/blog/item/b0b96d6f972e7dd080cb4a06.html


typeofkeyword是C语言中的一个新扩展。仅仅要能够接受typedef名称,Sun Studio C 编译器就能够接受带有typeof的结构,包含下面语法类别:

  • 声明
  • 函数声明符中的參数类型链表和返回类型
  • 类型定义
  • 类型操作符s
  • sizeof操作符
  • 复合文字
  • typeof实參

编译器接受带双下划线的keyword:__typeof__typeof__。本文中的样例并没有遵循使用双下划线的惯例。从语句构成上看,typeofkeyword后带圆括号,当中包括类型或表达式的名称。这类似于sizeofkeyword接受的操作数(与sizeof不同的是,位字段同意作为typeof实參,并被解释为对应的整数类型)。从语义上看,typeof keyword将用做类型名(typedef名称)并指定类型。

使用typeof的声明演示样例

以下是两个等效声明,用于声明int类型的变量a

typeof(int) a; /* Specifies variable a which is of the type int */ 
typeof('b') a; /* The same. typeof argument is an expression consisting of 
                    character constant which has the type int */

下面演示样例用于声明指针和数组。为了进行对照,还给出了不带typeof的等效声明。

typeof(int *) p1, p2; /* Declares two int pointers p1, p2 */
int *p1, *p2;

typeof(int) * p3, p4;/* Declares int pointer p3 and int p4 */
int * p3, p4;

typeof(int [10]) a1, a2;/* Declares two arrays of integers */

int a1[10], a2[10];

假设将typeof用于表达式,则该表达式不会运行。仅仅会得到该表达式的类型。下面演示样例声明了int类型的var变量,由于表达式foo()int类型的。由于表达式不会被运行,所以不会调用foo函数。

extern int foo();
typeof(foo()) var;

使用typeof的声明限制

请注意,typeof构造中的类型名不能包括存储类说明符,如externstatic。只是同意包括类型限定符,如constvolatile。比如,下列代码是无效的,由于它在typeof构造中声明了extern

typeof(extern int) a;

下列代码使用外部链接来声明标识符b是有效的,表示一个int类型的对象。下一个声明也是有效的,它声明了一个使用const限定符的char类型指针,表示指针p不能被改动。

extern typeof(int) b;
typeof(char * const) p = "a";

在宏声明中使用typeof

typeof构造的主要应用是用在宏定义中。能够使用typeofkeyword来引用宏參数的类型。


原文地址:https://www.cnblogs.com/zfyouxi/p/4079769.html