為原有數(shù)據(jù)類型起一個別名而已,并沒有憑空出現(xiàn)一個新的內(nèi)存形式。
int a = 170; // 根本看不出來a是什么含義,只知道開辟了一段int大小的內(nèi)存,放了170進(jìn)去
int b = 3600; // 根本看不出來b是什么含義
// 代碼可讀性非常差!
typedef int len_t;
typedef int time_t;
len_t a = 170; // 大致可以猜出a描述的是一個長度
time_t b = 3600; // 大致可以猜出b描述的是一個時間
// 這樣的代碼可讀性好了很多!
// _t:typedef 的意思。看到_t,就說明是使用typedef定義的外號。
用處:
建議不再使用通用的關(guān)鍵字(int等),而更多地使用一些見名知義的關(guān)鍵字,讓可讀性更好。——使用typedef
-
typedef與指針結(jié)合使用后,會非常非常方便和清晰,應(yīng)用會更加廣闊。
指針如果多了,就是一堆*
,非常不方便閱讀和維護(hù)。使用typedef后,定義一些變量會更加方便。typedef char* name_t; // name_t是一個指針類型的名稱/別名,指向了一個char類型的內(nèi)存。 name_t abc;
例1:
#include <stdio.h>
typedef struct Student
{
int sid;
char name[100];
char sex;
} ST;
int main()
{
ST st; //struct Student st;
ST * ps = &st; // struct Student *ps = &st;
st.sid = 200;
printf("%d\n",st.sid);
return 0;
}
例2:
#include <stdio.h>
typedef struct Student
{
int sid;
char name[100];
char sex;
}* PSTU, STU;
// PSTU等價于struct Student *
// STU等價于struct Student
int main()
{
STU st;
PSTU ps = &st;
ps->sid = 200;
printf("%d\n",ps->sid);
return 0;
}
例3:
#include <stdio.h>
typedef struct Student
{
int sid;
char name[100];
char sex;
} STU, *PSTU;
// STU等價于struct Student
// PSTU等價于struct Student *
int main()
{
STU st;
PSTU ps = &st;
ps->sid = 200;
printf("%d\n",ps->sid);
return 0;
}