呼唤远方
一、对枚举型的变量赋值。 实例将枚举类型的赋值与基本数据类型的赋值进行了对比: 方法1:先声明变量,再对变量赋值1234567891011121314151617#include<stdio.h>/* 定义枚举类型 */enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN };void main(){ /* 使用基本数据类型声明变量,然后对变量赋值 */ int x, y, z; x = 10; y = 20; z = 30; /* 使用枚举类型声明变量,再对枚举型变量赋值 */ enum DAY yesterday, today, tomorrow; yesterday = MON; today = TUE; tomorrow = WED; printf("%d %d %d \n", yesterday, today, tomorrow);} 方法2:声明变量的同时赋初值12345678910111213#include <stdio.h>/* 定义枚举类型 */enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN };void main(){ /* 使用基本数据类型声明变量同时对变量赋初值 */ int x=10, y=20, z=30; /* 使用枚举类型声明变量同时对枚举型变量赋初值 */ enum DAY yesterday = MON, today = TUE, tomorrow = WED; printf("%d %d %d \n", yesterday, today, tomorrow);} 方法3:定义类型的同时声明变量,然后对变量赋值。12345678910111213141516#include <stdio.h>/* 定义枚举类型,同时声明该类型的三个变量,它们都为全局变量 */enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN } yesterday, today, tomorrow;/* 定义三个具有基本数据类型的变量,它们都为全局变量 */int x, y, z;void main(){ /* 对基本数据类型的变量赋值 */ x = 10; y = 20; z = 30; /* 对枚举型的变量赋值 */ yesterday = MON; today = TUE; tomorrow = WED; printf("%d %d %d \n", x, y, z); //输出:10 20 30 printf("%d %d %d \n", yesterday, today, tomorrow); //输出:1 2 3} 方法4:类型定义,变量声明,赋初值同时进行。1234567891011121314151617181920#include <stdio.h>/* 定义枚举类型,同时声明该类型的三个变量,并赋初值。它们都为全局变量 */enum DAY{ MON=1, TUE, WED, THU, FRI, SAT, SUN }yesterday = MON, today = TUE, tomorrow = WED;/* 定义三个具有基本数据类型的变量,并赋初值。它们都为全局变量 */int x = 10, y = 20, z = 30;void main(){ printf("%d %d %d \n", x, y, z); //输出:10 20 30 printf("%d %d %d \n", yesterday, today, tomorrow); //输出:1 2 3} 2、对枚举型的变量赋整数值时,需要进行类型转换。1234567891011#include <stdio.h>enum DAY { MON=1, TUE, WED, THU, FRI, SAT, SUN };void main(){ enum DAY yesterday, today, tomorrow; yesterday = TUE; today = (enum DAY) (yesterday + 1); //类型转换 tomorrow = (enum DAY) 30; //类型转换 //tomorrow = 3; //错误 printf("%d %d %d \n", yesterday, today, tomorrow); //输出:2 3 30} 3、使用枚举型变量123456789101112131415161718192021222324252627282930#include<stdio.h>enum{ BELL = '\a', BACKSPACE = '\b', HTAB = '\t', RETURN = '\r', NEWLINE = '\n', VTAB = '\v', SPACE = ' '};enum BOOLEAN { FALSE = 0, TRUE } match_flag;void main(){ int index = 0; int count_of_letter = 0; int count_of_space = 0; char str[] = "I'm Ely efod"; match_flag = FALSE; for(; str[index] != '\0'; index++) if( SPACE != str[index] ) count_of_letter++; else { match_flag = (enum BOOLEAN) 1; count_of_space++; }printf("%s %d times %c", match_flag ? "match" : "not match", count_of_space, NEWLINE); printf("count of letters: %d %c%c", count_of_letter, NEWLINE, RETURN);}