C/C++,關鍵字typeof的用法

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章