在 C 语言中使用 typedef enum
本文将演示关于如何在 C 语言中使用 typedef enum
的多种方法。
使用 enum
在 C 语言中定义命名整数常量
enum
关键字定义了一种叫做枚举的特殊类型。枚举基本上只是整数值,其名称为变量,但却是只读对象,在运行时不能修改。
构造一个枚举对象有两种方法,一种是声明每个成员,不分配显式值,而是根据位置自动推导值;另一种是声明成员,分配显式值。
在下面的例子中,我们为每个成员分配自定义值,并将对象命名为-STATE
。接下来,我们就可以在代码中把 STATE
对象的成员名作为有符号整数,并在表达式中对其进行评估。下面的示例代码演示了多个条件语句,检查输入的整数是否等于定义的常量,一旦匹配,就打印出相应的合适的字符串。
#include <stdio.h>
#include <stdlib.h>
enum STATE{
RUNNING = 49,
STOPPED = 50,
FAILED = 51,
HIBERNATING = 52
};
int main(void) {
int input1;
printf("Please provide integer in range [1-4]: ");
input1 = getchar();
if (input1 == STOPPED) {
printf("Machine is stopped\n");
} else if (input1 == RUNNING) {
printf("Machine is running\n");
} else if (input1 == FAILED) {
printf("Machine is in failed state\n");
} else if (input1 == HIBERNATING) {
printf("Machine is hibernated\n");
}
exit(EXIT_SUCCESS);
}
输出:
Please provide integer in range [1-4]: 2
Machine is running
使用 typedef enum
定义包含命名整数常量的对象的定制类型
typedef
关键字用于命名用户定义的对象。在代码中经常需要多次声明结构。如果不使用 typedef
来定义它们,每次声明都需要以 struct
/enum
关键字开始,这就使得代码的可读性变得很重。
但请注意,typedef
只是为给定类型创建一个新的别名,而不是创建一个新的类型。许多整数类型如 size_t
、uint
等只是其他内置类型的 typedef
。因此,用户可以为内置类型声明多个别名,然后使用已经创建的别名来链式声明额外的 typedef
。
#include <stdio.h>
#include <stdlib.h>
typedef enum{
RUNNING = 49,
STOPPED = 50,
FAILED = 51,
HIBERNATING = 52
} MACHINE_STATE;
int main(void) {
int input1;
MACHINE_STATE state;
printf("Please provide integer in range [1-4]: ");
input1 = getchar();
state = input1;
switch (state) {
case RUNNING:
printf("Machine is running\n");
break;
case STOPPED:
printf("Machine is stopped\n");
break;
case FAILED:
printf("Machine is in failed state\n");
break;
case HIBERNATING:
printf("Machine is hibernated\n");
break;
default:
break;
}
exit(EXIT_SUCCESS);
}
输出:
Please provide integer in range [1-4]: 2
Machine is running
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn