C Primer Plus外藩(一)---枚举

枚举类型:
1.1枚举类型声明int 类型的常量,使用关键字enum。
使用枚举类型的目的是提高程序的可读性

#include <stdio.h>
int main(void){
    enum a {red,blue,green,populer,white,blach};
    enum a c;
    c = blue;
    printf("%d\n",c);
} 

结果 = 1;

#include <stdio.h>

int main(void){

    enum a {red = 100,blue,green,populer,white,blach};


    enum a c;

    c = blue;

    printf("%d\n",c);

} 

结果 = 101

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

enum spectrum { red,orange,yellow,green,blue,violet};
const char *colors[] = {"red","orange","yellow","green","blue","violet"};
#define LEN 30
int main(void){

    char choice[LEN];

    enum spectrum color;

    bool color_is_found = false;

    puts("Enter a color (empty line to quiet):");

    while(gets(choice)!= NULL & choice[0] != '0'){

        for(color = red;color <= violet;color ++){

            if(strcmp(choice,colors[color]) == 0){

                color_is_found = true ;
                break;
            }
        }

        if(color_is_found)
            switch(color){
                case red   : puts("rose are red");break;
                case orange: puts("poppies are orange");break;
                case yellow: puts("sunflower is yellow");break;
                case green : puts("grass is green"); break;
                case blue  : puts("bluebells is blue");break;
                case violet: puts("violet is voilet"); break;
            }

        else

            printf("i do not know about the color %s.\n",choice);

            color_is_found = false;
            puts("next colors please(empty line to quiet):");   

    }
    puts("goodbye!");   
    return 0;
}

名字相同但是具有不同的作用域不会起冲突,名字空间是分类别的。这意味着可以在同一个作用域内对一个变量和一个标记使用同一个名字,而不会产生错误

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值