C 語言中的 typedef enum 可以分開來看
typedef 用來對一個資料類型取一個新名字。目的是為了讓程式碼更好讀更好理解
舉個例子:
我們來為int取個可愛的名字 這樣看起來比較順眼
未使用 typedef 的樣貌
int color; //宣告color 為一變數
int leaf; // 宣告leaf 為一變數
...
...
...
使用 typedef 後的樣貌 ->
typedef int Apple; // int 的名子為Apple(蘋果) typedef int Orange; // int 的名字Orange(橘子)
Apple color; //宣告color 為一變數
Orange leaf; // 宣告leaf 為一變數
...
...
...
另一個更常見的例子是用在幫結構(struct)取名子
未使用 typedef 的樣貌
struct var {
int math;
int english;
char data3;
};struct var yo;
這個結構以往在C當中要使用就要用這樣的方式
struct var yo;
但是只要使用 typedef 就能改名了 如下
typedef struct var results;
這樣之後要使用時就能改成這樣
results yo;
完整用法
struct var {
int math;
int english;
char data3;
};typedef struct var results;
results yo;
enum 是英文 enumerate(列舉,枚舉) 的縮寫
效果是列舉出多個'常數',並設定數值。
例子:
enum{
stop,
stand,
run
};
大括號中每一個元素稱為列舉元。
如果沒設定數值,預設是從0開始遞增。(stop=0 ; stand=1 ; run=2)
如果要設定數值,可以這樣打
enum{
stop=5,
stand,
run
};
這樣就會變成 (stop=5 ; stand=6 ; run=7)
也可以這樣用
enum{
stop=5,
stand,
run=2
};
這樣會變成 (stop=5 ; stand=6 ; run=2)
各自介紹完後
最後舉個簡單的例子
#include<stdio.h>
#include<stdlib.h>
typedef enum{
All,
January,
February,
March,
April,
May
}month;
month Month;
int mon;
main(){
printf("隨意輸入1到5之間的一個數");
scanf("%d",&mon);
switch(mon){
case January:
printf("一月"); break;
case February:
printf("二月"); break;
case March:
printf("三月"); break;
case April:
printf("四月"); break;
case May:
printf("五月"); break;
default:
printf("要輸入1到5之間的數喔");
}
system("PAUSE");
}
留言列表