关键词搜索

源码搜索 ×
×

C语言中枚举类型的重要应用

发布2013-03-17浏览8471次

详情内容

       先看:

  1. #include <stdio.h>
  2. int main()
  3. {
  4. int Red = 0;
  5. int Green = 1;
  6. int Blue = 2;
  7. printf("%d\n", Red);
  8. printf("%d\n", Green);
  9. printf("%d\n", Blue);
  10. return 0;
  11. }

       下面用宏定义实现:

 

  1. #include <stdio.h>
  2. #define RED 0
  3. #define GREEN 1
  4. #define BLUE 2
  5. int main()
  6. {
  7. printf("%d\n", RED);
  8. printf("%d\n", GREEN);
  9. printf("%d\n", BLUE);
  10. return 0;
  11. }

       最后看看用枚举类型如何来实现:

 

 

  1. #include <stdio.h>
  2. typedef enum
  3. {
  4. Red,
  5. Green,
  6. Blue
  7. }Color;
  8. int main()
  9. {
  10. printf("%d\n", Red);
  11. printf("%d\n", Green);
  12. printf("%d\n", Blue);
  13. return 0;
  14. }

 

    最后来欣赏两个程序:

 

 

  1. #include <stdio.h>
  2. void print(int flag)
  3. {
  4. if(0 == flag)
  5. printf("red\n");
  6. if(1 == flag)
  7. printf("green\n");
  8. if(2 == flag)
  9. printf("blue\n");
  10. }
  11. int main()
  12. {
  13. print(0);
  14. print(1);
  15. print(2);
  16. return 0;
  17. }

 

  1. #include <stdio.h>
  2. typedef enum
  3. {
  4. Red,
  5. Green,
  6. Blue
  7. }Color;
  8. void print(Color c)
  9. {
  10. if(Red == c)
  11. printf("red\n");
  12. if(Green == c)
  13. printf("green\n");
  14. if(Blue == c)
  15. printf("blue\n");
  16. }
  17. int main()
  18. {
  19. print(Red);
  20. print(Green);
  21. print(Blue);
  22. return 0;
  23. }

      可见,用枚举,程序的意义更清晰,更好。

 

      在C语言中,没有bool类型,那怎么办呢?

 

  1. #include <stdio.h>
  2. typedef enum
  3. {
  4. FALSE,
  5. TRUE
  6. }BOOL;
  7. BOOL isPositive(int n)
  8. {
  9. if(n > 0)
  10. return TRUE;
  11. return FALSE;
  12. }
  13. int main()
  14. {
  15. int a = 1;
  16. if(isPositive(a))
  17. printf("positive\n");
  18. else
  19. printf("not\n");
  20. return 0;
  21. }

 

 

 

 

 

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载