先看:
- #include <stdio.h>
-
- int main()
- {
- int Red = 0;
- int Green = 1;
- int Blue = 2;
-
- printf("%d\n", Red);
- printf("%d\n", Green);
- printf("%d\n", Blue);
-
- return 0;
- }
下面用宏定义实现:
- #include <stdio.h>
- #define RED 0
- #define GREEN 1
- #define BLUE 2
-
- int main()
- {
- printf("%d\n", RED);
- printf("%d\n", GREEN);
- printf("%d\n", BLUE);
-
- return 0;
- }
最后看看用枚举类型如何来实现:
- #include <stdio.h>
-
- typedef enum
- {
- Red,
- Green,
- Blue
- }Color;
-
- int main()
- {
- printf("%d\n", Red);
- printf("%d\n", Green);
- printf("%d\n", Blue);
-
- return 0;
- }
最后来欣赏两个程序:
- #include <stdio.h>
-
- void print(int flag)
- {
- if(0 == flag)
- printf("red\n");
- if(1 == flag)
- printf("green\n");
- if(2 == flag)
- printf("blue\n");
-
-
- }
-
- int main()
- {
- print(0);
- print(1);
- print(2);
-
- return 0;
- }
- #include <stdio.h>
-
- typedef enum
- {
- Red,
- Green,
- Blue
- }Color;
-
- void print(Color c)
- {
- if(Red == c)
- printf("red\n");
- if(Green == c)
- printf("green\n");
- if(Blue == c)
- printf("blue\n");
-
- }
-
- int main()
- {
- print(Red);
- print(Green);
- print(Blue);
-
- return 0;
- }
可见,用枚举,程序的意义更清晰,更好。
在C语言中,没有bool类型,那怎么办呢?
- #include <stdio.h>
-
- typedef enum
- {
- FALSE,
- TRUE
- }BOOL;
-
- BOOL isPositive(int n)
- {
- if(n > 0)
- return TRUE;
-
- return FALSE;
- }
-
- int main()
- {
- int a = 1;
- if(isPositive(a))
- printf("positive\n");
- else
- printf("not\n");
-
- return 0;
- }