zoukankan      html  css  js  c++  java
  • C语言入门-枚举

    常量符号化

    用符号而不是具体的数字来表示程序中的数字

    一、 枚举

    用枚举而不是定义独立的const int变量

    1. 枚举是一种用户定义的数据类型,它用关键字enum如以下语句来声明
    enum 枚举类型名字 {名字0 ,、、、 , 名字n};
    
    1. 枚举类型名字通常并不真的使用,要用的是在大括号里的名字,因为它们就是常量符号,他们的类型是int,值则依次从0到,如:
    enum colors {red , yellow , green};
    
    1. 就创建了三个常量,red的值0,yellow是1,green是2
    2. 当需要一些可以排列起来的常量值时,定义枚举的意义就是给了这些常量值名字
    #include <stdio.h>
    
    enum color {red , yellow , green};
    
    
    void f(enum color c);
    
    int main(void)
    {
    	enum color t = yellow;
    
    	// scanf("%d" , &t);
    	f(t);
    
    	return 0;
    }
    
    
    
    void f(enum color c)
    {
    	printf("%d
    ", c);
    }
    
    // 1
    // 因为yellow的下标是1
    

    注意:

    1. 枚举量可以作为值
    2. 枚举类型可以跟上enum作为类型
    3. 但是实际上是以整数来做内部计算和外部输入输出的

    二、自动计数的枚举

    这样需要遍历所有的枚举量或者需要建立一个用枚举量做下标的数组的时候很方便

    enum COLOR {RED , YELLOW , GREEN , NumCOLLORS};
    
    int main(int argc, char const *argv[])
    {
    	int color = -1;
    
    	char *ColorNames[NumCOLLORS] = {
    		"red" , "yellow" , "green"
    	};
    	char *colorName = NULL;
    
    	printf("请输入你喜欢的颜色代码:
    ");
    	scanf("%d" , &color);
    
    	if(color >= 0 && color <NumCOLLORS){
    		colorName = ColorNames[color];
    	}else{
    		colorName = "nuknow";
    	}
    
    	printf("你喜欢的颜色是%s
    ", colorName);
    
    
    	return 0;
    }
    
    //请输入你喜欢的颜色代码:
    //2
    //你喜欢的颜色是green
    
    

    三、枚举量

    1. 声明枚举量的时候可以指定值
    2. enum COLOR {RED=1 , YELLOW , GREEN = 5 , NumCOLLORS};
    enum COLOR {RED=1 , YELLOW , GREEN = 5 , NumCOLLORS};
    
    int main(int argc, char const *argv[])
    {
    	printf("code for GREEN is %d
    " , GREEN);
    	return 0;
    }
    // code for GREEN is 5
    

    四、枚举只是int

    即使给枚举类型的变量赋不存在的整数值也没有任何error

    enum COLOR {RED=1 , YELLOW , GREEN = 5 , NumCOLLORS};
    
    int main(int argc, char const *argv[])
    {
    	enum COLOR color = 0;
    	printf("code for GREEN is %d
    " , GREEN);
    	printf("and color is %d
    ", color);
    	return 0;
    }
    // code for GREEN is 5
    // and color is 0
    
    

    枚举

    1. 虽然枚举类型可以当作类型使用,但是实际上很少使用
    2. 如果有意义上排比的名字,用枚举比const int 方便
    3. 枚举比宏好,因为枚举有int类型
  • 相关阅读:
    运算符重载
    C++ 画星号图形——圆形(核心代码记录)
    C++ 画星号图形——空心三角形(星号左对齐)(核心代码介绍)
    C++ 画星号图形——空心三角形(星号居中对齐)(核心代码介绍)
    QMap迭代器
    QVector也是隐式数据共享的
    调试dump文件
    How does the compilation and linking process work?
    when to use reinterpret_cast
    构造类的时候,提供类型转换
  • 原文地址:https://www.cnblogs.com/mengd/p/11667842.html
Copyright © 2011-2022 走看看