C语言枚举类型使用简介

1:枚举里面的 值是 常量 ;    例如 enum color {red,orange,yellow};

2:枚举列表中的常量默认为0,1,2等等  例如 enum color {red,orange,yellow};  常量值默认为0,1,2

3:  枚举列表常量值是可以指定的,且指定值后的枚举值将递增   例如enum color {red,orange=10,yellow}; yellow=11

4:  在C语言中枚举可以递增 运算符++,而C++中需要强制转换定义为int再运算符++

 

enum用法例子如下

 

#include < stdio.h >
#include < string .h >
enum   specturm {red,orange,yellow,green,blue,violet};
const   char   * colors[] = { " red " , " orange " , " yellow " , " green " , " blue " , " violet " };
#define  LEN 30
int  main( void )
{
    
char  choice[LEN];
    
int  color;
    
int   color_is_found = 0 ;
    puts( " Enter a color (empty line to quit):  " );
    
while (gets(choice) != NULL && choice[ 0 ] != ' \0 ' )
    {
        
for (color = red;color <= violet;color ++ )
        {
            
if (strcmp(choice,colors[color]) == 0 )
            {
                color_is_found = 1 ;
                
break ;
            }
        }
        
if (color_is_found)
        
switch (color)
        {
            
case   0 :puts( " Roses are red " ); break ;
            
case   1 :puts( " Poppies are orange " ); break ;
            
case   2 :puts( " Sunflowers are yellow " ); break ;
            
case   3 : puts( " Grass is green " ); break ;
            
case   4 :puts( " Bluebells are blue " ); break ;
            
case   5 :puts( " Violets are violet " ); break ;
        }
        
else  printf( " I don't know about the color %s.\n " ,choice);
        color_is_found = 0 ;
        puts( " Next color,please(empty line to quit):  " );
    }
    puts( " Goodbye! " );
    
return   0 ;
}

你可能感兴趣的:(C语言)