The C Programming Language

列舉(enum)
CSIM, PU
C Language
列舉型態
 列舉型態(enumeration)是一種特殊的常數定義方式。
 列舉型態可使我們定義自己的資料型態,及設定其值。
 程式的可讀性提高。
 列舉型態的定義及宣告方式格式如下:
enum 列舉型態名稱
{
列舉常數1,
定義列舉型態
列舉常數2,
…
列舉常數n,
};
enum 列舉型態名稱 變數1,變數2,…,變數m;
CSIM, PU
C Language
2
範例
 範例(定義與宣告變數分開):
enum color
{
red,
定義列舉型態color
blue,
green,
};
enum color coat, hat;
/*宣告列舉型態color之變數coat與hat */
 範例(定義後立即宣告變數):
enum color
/*宣告列舉型態color */
{
red,
列舉常數
blue,
green,
} coat , hat;
/*定義完列舉型態後,立即宣告變數coat與hat */
CSIM, PU
C Language
3
 減少程式行數的寫法:
ex1: enum color{ red, blue, green} coat, hat;
ex2: enum week{ Sun, Mon, Tue, Wed, Thu, Fri, Sat};
ex3: enum cars{ Benz, BMW, Audi, Accord};
enum cars mycar, yourcar;
mycar,yourcar這兩個變數以enum cars為其資料型態
,且這兩個變數的可能值不可能是列舉子以外的值。
mycar =Lotus; ---不合法
yourcar=Mini; ----不合法
CSIM, PU
C Language
4
enum的使用與初值設定
 宣告列舉型態變數後,這個變數的值就只能是列舉常數裡的其
中一個。
 無特別指定的情況下,C語言會自動給列舉常數一個整數值,
列舉常數1的值為0,列舉常數2的值為1以此類推…..
 上一頁的範例中,我們定義了列舉型態color,並宣告該列舉
型態的變數coat與hat,沒有特別指定下,編譯程式將列舉常數
從0開始的整數看待,red的值會視為0,blue的值視為1,green
的值視為2。
 可以改變其內定值:
ex: enum color { red=10, blue, green};
CSIM, PU
C Language
5
列舉型態的使用-範例1
#include<stdio.h>
int main(void)
列舉型態的變數所佔的位元組與整數型態相同,皆為4個位元組
{
enum color
{
red,
green,
blue,
}hat;
printf("sizeof(hat)=%d\n",sizeof(hat));
printf("red=%d\n",red);
printf("green=%d\n",green);
printf("blue=%d\n",blue);
hat=blue;
if(hat==blue)
printf("你選擇了藍色的帽子\n");
else
printf("你選擇了非藍色的帽子\n");
system("pause");
return 0;
}
CSIM, PU
C Language
6
列舉型態的使用-範例2
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
enum per{manager,SE,SA,sales};
struct{
char name[20];
float salary;
enum per category;
}employee;
strcpy(employee.name,"Andy");
將Andy字串複製到結構employee的name成員
employee.salary=25000;
employee.category=SE;
printf("Name=%s\n",employee.name);
printf("Salary=%6.2f\n",employee.salary);
printf("Category=%d\n",employee.category);
if(employee.category==manager)
printf("%s is a manager.",employee.name);
else
printf("%s is not a manager.\n",employee.name);
system("pause");
return 0;
CSIM, PU
C Language
7
typedef
 typedef 可以重新定義資料型態的名稱。
 格式如下:
typedef 資料型態 識別字;
ex:
typedef unsigned int BYTE;
表示BYTE與unisgned int 具有相同的效果
(1) typedef unsigned int BYTE;
BYTE num1,num2;
(2) unsigned int num1,num2;
CSIM, PU
意義相同
C Language
8
 將結構改以typedef定義
struct student
typedef struct student
{
{
int id;
int id;
char name[20];
char name[20];
int score;
int score;
};
} ST;
struct student st1;
ST st1;
以ST來定義,而不需struct student一長串
的資料型態名稱。
CSIM, PU
C Language
9
Typedef使用範例
#include<stdio.h>
#include<string.h>
void main()
{
typedef struct student
{
int id;
char name[20];
int score;
}ST;
ST st1;
st1.id=2005;
strcpy(st1.name,"Johnson");
st1.score=80;
printf("%d %s %d\n",st1.id,st1.name,st1.score);
system("pause");
}
CSIM, PU
C Language
10