1. 程式人生 > >C語言中 typeof()函式的用法

C語言中 typeof()函式的用法

前言:

    typeof關鍵字是C語言中的一個新擴充套件,這個特性在linux核心中應用非常廣泛。


一,說明
    typeof的引數可以是兩種形式: 表示式 型別

     1,表示式的的例子:
        typeof(x[0](1)
        這裡假設x是一個函式指標陣列,這樣就可以得到這個函式返回值的型別了。

        如果將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];

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

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

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

            int a1[10], a2[10];


    7,定義一個巨集返回一個最大值,為避免因為重複呼叫同一個變數,可以這樣     

       把     MAX(x,y)  ((x)>(y)?(x):(y))


       改成   MAX(x,y)   ({   typeof(x) _x=x;\

typeof(x) _y=y;\

_x>_y?_x:_y;\

    })



,侷限
    typeof構造中的型別名 不能 包含儲存類說明符,如 extern static 。不過允許包含型別限定符,如 const volatile
    例如,下列程式碼是無效的,因為它在typeof構造中聲明瞭extern:
        typeof(extern int) a;



四,檔案參考
    1,http://blog.csdn.net/wslong/article/details/7728811
    2,http://gcc.gnu.org/onlinedocs/gcc/Typeof.html#Typeof