前言
typeof() 是GUN C提供的一種特性,可參考C-Extensions,它可以取得變量的類型,或者表達式的類型。
本文總結了typeof()關鍵字的常見用法,並給出了相應的例子,以加深理解 。
typeof()關鍵字常見用法
typeof()關鍵字常見用法一共有以下幾種。
-
不用知道函數返回什麼類型,可以使用typeof()定義一個用於接收該函數返回值的變量
#include <stdio.h> #include <stdlib.h> #include <string.h> struct apple{ int weight; int color; }; struct apple *get_apple_info() { struct apple *a1; a1 = malloc(sizeof(struct apple)); if(a1 == NULL) { printf("malloc error.\n"); return; } a1->weight = 2; a1->color = 1; return a1; } int main(int argc, char *argv[]) { typeof(get_apple_info()) r1;//定義一個變量r1,用於接收函數get_apple_info()返回的值,由於該函數返回的類型是:struct apple *,所以變量r1也是該類型。注意,函數不會執行。 r1 = get_apple_info(); printf("apple weight:%d\n", r1->weight); printf("apple color:%d\n", r1->color); return 0; }
-
在宏定義中動態獲取相關結構體成員的類型
如下代碼,定義一個和變量x相同類型的臨時變量_max1,定義一個和變量y相同類型的臨時變量_max2,再判斷兩者類型是否一致,不一致給出一個警告,最後比較兩者。
#define max(x, y) ({ \ typeof(x) _max1 = (x); \ typeof(y) _max2 = (y); \ (void) (&_max1 == &_max2); \//如果調用者傳參時,兩者類型不一致,在編譯時就會發出警告。 _max1 > _max2 ? _max1 : _max2; })
如下代碼,傳入的a和b不是同一類型。
int main(int argc, char *argv[]) { int a=3; float b = 4.0; int r = max(a, b); printf("r:%d\n", r); return 0; }
此時編譯就會出現警告
[root@xx c_base]# gcc test.c test.c: 在函數‘main’中: test.c:43: 警告:比較不相關的指針時缺少類型轉換
-
也可直接取得已知類型
如下代碼,定義了一個int類型的指針p,像這種用法主沒什麼太大的意義了。
int a = 2; typeof (int *) p; p = &a; printf("%d\n", *p);
-
其它用法
//其它用法1
char *p1;
typeof (*p1) ch = 'a'; //ch爲char類型,不是char *類型。
printf("%d, %c\n", sizeof(ch), ch);//1, a
//其它用法2
char *p2;
typeof (p2) p = "hello world";//此時的p纔是char *類型,由於在64位機器上,所以指針大小爲8字節
printf("%d, %s\n", sizeof(p), p);//8, hello world
總結
以上例子並沒有窮舉所有的情況,但其核心用法基本上就會了,其它的例子也可參考網上的例子。