c语言枚举类型代替常量const int类型

1.枚举类型的语法格式:enmu 枚举类型名称 {单个元素名称,单个元素名称};

enum COLOR {Blue, Red, Green};

枚举类型中的Blue相当于整型0,Red是1,Grenn是2…默认是从0开始
定义枚举类型时,不一定从零开始,例如:

enum COLOR {Blue = 2, Red = 1, Green};

此时的Green是2,根据上一个元素的顺序往下排列。

enum COLOR {Blue = 2, Red = 9, Green};

此时的Green是10

2.定义枚举类型时的小技巧:在最后面加上一个用来表示数量的元素。

enum COLOR {Blue, Red, Grenn, AmountOfColor};

此时的AmountOfColor等于3,3刚好表示了前三个元素。
1)可以使用AmountOfColor来创建包含三个元素的数组,遍历数组(我觉得还是用数组lenght属性最好)
2)可以使用AmoutnOfColor来判断用户输入是不是在枚举类型的范围内部。

int color = -1scanf("请输入喜欢的颜色,0表示蓝色,1表示红色,2表示绿色"&color);
if(color < AmoutnOfColor && color >= 0)
{
	//do something
}

3.使用符号去表示数字,而不是直接使用数字。因为数字降低了代码的可读性。

#include<stdio.h>
//常量类型
const int blue = 1, red = 2, green = 3;
int main(int argc, char const *argv[])
{
    int color = -1;
    printf("请输入你喜欢的颜色!");
    printf("1表示蓝色,2表示红色,3表示绿色");

    scanf("%d",&color);

    switch (color)
    {
    case blue:
        printf("blue");
        break;
    
    case red:
        printf("red");
        break;
    
    case green:
        printf("green");
        break;
    }    
    
}

4.使用枚举类型代替const int 常量类型

#include<stdio.h>
//枚举类型
enum color {Red, Blue, Green};
int main(int argc, char const *argv[])
{
    int userColor = -1;
    printf("0代表红色,1代表蓝色,2代表绿色");
    scanf("%d", &userColor);
    
    switch (userColor)
    {
    //可以直接使用Red,Blue,Green比直接定义const int更方便一些
    case Red:
        printf("Red");
        break;
    case Blue:
        printf("Blue");
        break;
    case Green:
        printf("Green");
        break;
    }


    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘璐菲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值