C/C++,关键字typeof的用法

来源:互联网 发布:淘宝上可以贷款吗 编辑:程序博客网 时间:2024/05/17 05:15

typeof (alternately typeOf or TypeOf) is an operator provided by several programming languages which determines the data type of a given variable. This can be useful when constructing parts of programs that need to accept many types of data but may need to take different action depending on the type of data provided.

上述引用摘自维基百科 - Typeof

Typeof用于指定变量的数据类型,该关键字使用时的语法类似sizeof,但是其结构在语义上类似于用typedef定义的类型名称。
Typeof有两种形式的参数:表达式 或者 类型。

下面是使用表达式作为参数的例子:

typeof(x[0](1))

在此假设x是一个函数指针数组;该类型描述的是函数返回值。

下面是使用类型作为参数的例子:

typeof(int *)

在此该类型描述的是一个指向int的指针。

如果在一个被包含在ISO C程序中的头文件中使用该关键字,请使用__typeof__代替typeof。
typeof可用在任何可使用typedef的地方,例如,可将它用在声明,sizeof或typeof内。

typeof在声明中与表达式结合非常有用,下面是二者结合用来定义一个获取最大值的“宏“:

#define max(a,b) \       ({ typeof (a) _a = (a); \           typeof (b) _b = (b); \         _a > _b ? _a : _b; })

本地变量使用下划线命名是为了避免与表达式中的变量名a和b冲突。

下面是一些typeof使用示例:

  • 声明y为x指向的数据类型
typeof(*x) y;
  • 声明y为x指向的数据类型的数组
typeof(*x) y[4];
  • 声明y为字符指针数组
typeof(typeof(char *)[4]) y;

上述声明等价于 char *y[4];

Typeof在linux内中使用广泛,比如,宏container_of用于获取包含member的结构体type的地址:

/** * container_of - cast a member of a structure out to the containing structure * * @ptr:    the pointer to the member. * @type:   the type of the container struct this is embedded in. * @member: the name of the member within the struct. * */#define container_of(ptr, type, member) ({          \    const typeof( ((type *)0)->member ) *__mptr = (ptr);    \    (type *)( (char *)__mptr - offsetof(type,member) );})

文章部分译自https://gcc.gnu.org/onlinedocs/gcc/Typeof.html

0 0
原创粉丝点击