C语言-枚举类型


枚举类型

相关知识

1
1.不能直接对枚举变量赋整数值,需要将整数强制性转换

定义枚举类型和声明枚举变量

先定义枚举类型,在定义枚举变量

1
2
3
4
5
6
7
8
# include <stdio.h>

int main(){
enum Weekday{mon,tue,wed,thu,fri,sat,sun}; // 枚举元素(枚举常量)的值从0开始
enum Weekday workday;
workday=sun; //workday=6
return 0;
}

定义枚举类型的同时,声明枚举变量

1
2
3
4
5
6
7
# include <stdio.h>

int main(){
enum Weekday{mon,tue,wed=5,thu,fri,sat,sun} workday; // 枚举元素(枚举常量)的值从0开始依次以1递增,第三个从5开始以1递增
workday=sun; //workday=9
return 0;
}

不定义枚举类型,直接定义枚举变量

1
2
3
4
5
6
7
# include <stdio.h>

int main(){
enum {mon,tue,wed,thu,fri,sat,sun} workday; // 枚举元素(枚举常量)的值从0开始
workday=sun; //workday=6
return 0;
}

枚举元素连续的枚举变量可以遍历

1
2
3
4
5
6
7
8
9
# include <stdio.h>

int main(){
enum {mon,tue,wed,thu,fri,sat,sun} workday; // 枚举元素(枚举常量)的值从0开始
for(workday=mon;workday<=sun;day++){
printf("%d", workday);
}
return 0;
}

在switch中的使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
int main(){
enum color{red,green,blue} favorite_color;
scanf("%d",&favorite_color); // 但不能:favorite_color=1
switch(favorite_color){
case red:
break;
case green:
break;
case blue:
break;
}
return 0;
}

将整型转换成枚举

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>
int main(){
enum color{red,green,blue} favorite_color;
//scanf("%d",&favorite_color);
favorite_color=(enum color) 0;
switch(favorite_color){
case red:
printf("xxx");
break;
case green:
break;
case blue:
break;
}
return 0;
}

用枚举元素作判断

1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
int main(){
enum color{red,green,blue} favorite_color;
//scanf("%d",&favorite_color);
favorite_color=blue;
if(favorite_color>red){ //0
printf(">");
}
return 0;
}

本文标题:C语言-枚举类型

文章作者:TTYONG

发布时间:2022年10月09日 - 18:10

最后更新:2022年10月09日 - 18:10

原始链接:http://tianyong.fun/C%E8%AF%AD%E8%A8%80-%E6%9E%9A%E4%B8%BE%E7%B1%BB%E5%9E%8B.html

许可协议: 转载请保留原文链接及作者。

多少都是爱
0%