C語言第11課——typedof和#define
阿新 • • 發佈:2018-11-25
typedef
可以使用它來為型別取一個新的名字。
typedef unsigned char BYTE;
BYTE b1, b2;
按照慣例,定義時會大寫字母,以便提醒使用者型別名稱是一個象徵性的縮寫,但也可以使用小寫字母。
使用 typedef 來為使用者自定義的資料型別取一個新的名字。
例如,可以對結構體使用 typedef 來定義一個新的資料型別名字,然後使用這個新的資料型別來直接定義結構變數,如下:
#include <stdio.h> #include <string.h> typedef struct Books { char title[50]; char author[50]; char subject[100]; int book_id; } Book; int main( ) { Book book; strcpy( book.title, "C 教程"); strcpy( book.author, "Runoob"); strcpy( book.subject, "程式語言"); book.book_id = 12345; printf( "書標題 : %s\n", book.title); printf( "書作者 : %s\n", book.author); printf( "書類目 : %s\n", book.subject); printf( "書 ID : %d\n", book.book_id); return 0; }
#define
#define 是 C 指令,用於為各種資料型別定義別名,與 typedef 類似,但是它們有以下幾點不同:
- typedef 僅限於為型別定義符號名稱,#define 不僅可以為型別定義別名,也能為數值定義別名,比如可以定義 1 為 ONE。
- typedef 是由編譯器執行解釋的,#define 語句是由預編譯器進行處理的。
#include <stdio.h> #include <string.h> #define BOOK struct Books //給Struct Books定義別名BOOK #define ONE 1 //給數值1定義別名ONE struct Books { char title[50]; char author[50]; char subject[100]; int book_id; }; int main() { BOOK book = { "C 教程" ,"Runoob" ,"程式語言" ,ONE}; printf("書標題 : %s\n", book.title); printf("書作者 : %s\n", book.author); printf("書類目 : %s\n", book.subject); printf("書 ID : %d\n", book.book_id); return 0; }