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

本文详细介绍了Typeof操作符的功能及用法,包括其在不同上下文中如何确定变量的数据类型,以及如何在程序中有效利用Typeof来实现类型检查和灵活的类型处理。此外,还提供了多个使用案例,如定义获取最大值的宏和宏container_of的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值