枚举类型

作者:追风剑情 发布于:2020-3-13 10:09 分类:C

示例

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <stdbool.h>
  5. #include <string.h>
  6.  
  7. // 枚举类型的目的是为了提高程序的可读性和可维护性。
  8.  
  9. // 定义枚举 {常量值(int)}
  10. enum spectrum {red, orange, yellow, green, blue, violet};
  11. // 也可以指定常量值
  12. enum levels {low = 100, medium = 500, high = 2000};
  13. // cat=0, lynx=10, puma=11, tiger=12
  14. enum feline {cat, lynx = 10, puma, tiger};
  15. //enum
  16. // 声明枚举变量
  17. enum spectrum color;
  18.  
  19. int main(int argc, char* argv[])
  20. {
  21. int c;
  22. color = blue;
  23. if (color == yellow)
  24. {
  25.  
  26. }
  27.  
  28. // 枚举值实际上是int类型
  29. for (color = red; color <= violet; color++)
  30. {
  31.  
  32. }
  33.  
  34. // 只要是能使用整型常量的地方就可以使用枚举常量
  35. printf("red = %d, orange = %d\n", red, orange);
  36.  
  37. /*
  38. 虽然枚举符(如red和blue)是int类型,但是枚举变量可以是任意整数类型,前提是该整数类型
  39. 可以储存枚举常量。例如,spectrum的枚举符范围是0~5,所以编译器可以用unsigned char来表示
  40. color变量。
  41. */
  42.  
  43. /*
  44. 注意:C枚举的一些特性并不适用于C++。例如,C允许枚举变量使用++运算符,但是C++标准
  45. 不允许。所以,如果编写的代码将来会并入C++程序,那么必须把上面的color声明为int类型,
  46. 才能C和C++都兼容。
  47. */
  48.  
  49. system("pause");
  50. return 0;
  51. }

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号