C語言typedef 給型別起乙個別名

2021-07-25 11:11:09 字數 2965 閱讀 4285

c語言允許為乙個資料型別起乙個新的別名,就像給人起「綽號」一樣。

起別名的目的不是為了提高程式執行效率,而是為了編碼方便。例如有乙個結構體的名字是 stu,要想定義乙個結構體變數就得這樣寫:

struct stu stu1;

struct 看起來就是多餘的,但不寫又會報錯。如果為 struct stu 起了乙個別名 stu,書寫起來就簡單了:

stu stu1;

這種寫法更加簡練,意義也非常明確,不管是在標準標頭檔案中還是以後的程式設計實踐中,都會大量使用這種別名。

使用關鍵字

typedef可以為型別起乙個新的別名,語法格式為:

typedef  oldname  newname;

oldname 是型別原來的名字,newname 是型別新的名字。例如:

複製

格式化複製

typedef

int integer;

integer

a, b;

a =1

;b =2;

typedef int integer;

integer a, b;

a = 1;

b = 2;

integer a, b;等效於int a, b;

typedef 還可以給陣列、指標、結構體等型別定義別名。先來看乙個給陣列型別定義別名的例子:

typedef char array20[20];

表示 array20 是型別char [20]的別名。它是乙個長度為 20 的陣列型別。接著可以用 array20 定義陣列:

array20 a1, a2, s1, s2;

它等價於:

char a1[20], a2[20], s1[20], s2[20];

注意,陣列也是有型別的。例如char a1[20];定義了乙個陣列 a1,它的型別就是 char [20],這一點已在vip教程《

陣列和指標絕不等價,陣列是另外一種型別》中講解過。

又如,為結構體型別定義別名:

複製

格式化複製

typedef

struct

stu stu;

typedef struct stu stu;

stu 是 struct stu 的別名,可以用 stu 定義結構體變數:

stu body1,body2;

它等價於:

struct stu body1, body2;

再如,為指標型別定義別名:

typedef int (*ptr_to_arr)[4];

表示 ptr_to_arr 是型別int * [4]的別名,它是乙個二維陣列指標型別。接著可以使用 ptr_to_arr 定義二維陣列指標:

ptr_to_arr p1, p2;

按照類似的寫法,還可以為函式指標型別定義別名:

typedef int (*ptr_to_func)(int, int);

ptr_to_func pfunc;

【示例】為指標定義別名。

複製

格式化複製

#include

typedef

char

(*ptr_to_arr)[

30];

typedef

int(*ptr_to_func)(

int,

int);

intmax

(int a,

int b)

char str[3][

30]=;

intmain

()return0;

}

#include typedef char (*ptr_to_arr)[30];

typedef int (*ptr_to_func)(int, int);

int max(int a, int b)

char str[3][30] = ;

int main()

return 0;

}

執行結果:

max: 20

str[0]:

str[1]: c語言中文網

str[2]: c-language

需要強調的是,typedef 是賦予現有型別乙個新的名字,而不是建立新的型別。為了「見名知意」,請盡量使用含義明確的識別符號,並且盡量大寫。typedef 在表現上有時候類似於 #define,但它和巨集替換之間存在乙個關鍵性的區別。正確思考這個問題的方法就是把 typedef 看成一種徹底的「封裝」型別,宣告之後不能再往裡面增加別的東西。

1) 可以使用其他型別說明符對巨集型別名進行擴充套件,但對 typedef 所定義的型別名卻不能這樣做。如下所示:

#define interge int

unsigned interge n;  //沒問題

typedef int interge;

unsigned interge n;  //錯誤,不能在 interge 前面新增 unsigned

2) 在連續定義幾個變數的時候,typedef 能夠保證定義的所有變數均為同一型別,而 #define 則無法保證。例如:

#define ptr_int int *

ptr_int p1, p2;

經過巨集替換以後,第二行變為:

int *p1, p2;

這使得 p1、p2 成為不同的型別:p1 是指向 int 型別的指標,p2 是 int 型別。

相反,在下面的**中:

typedef int * ptr_int

ptr_int p1, p2;

p1、p2 型別相同,它們都是指向 int 型別的指標。

利用typedef給資料型別起別名

1.先定義列舉型別,再給列舉型別起別名 enum gender typedef enum gender 2.定義列舉型別的同時給列舉型別起別名 typedef enum gender 3.定義列舉型別的同時給列舉型別起別名,並且省略列舉原有型別名稱 typedef enum 1.先定義結構體型別,再...

給型別起別名

define crt secure no warnings include include include typedef unsigned int u32 typedef和結構體結合使用 struct mystruct typedef struct mystruct2 tmp void,無型別 1...

c語言之使用typedef定義型別

可以用typedef宣告新的型別名來代替已有的型別名。例項1 include include typedef struct student intmain 例項2 include include typedef int num 100 int main printf d n sizeof num s...