枚举(或枚举)是C语言中用户定义的数据类型。它主要用于将名称分配给整数常量,这些名称使程序易于阅读和维护。
enum State {Working = 1, Failed = 0};
关键字“ enum”用于在C和C++中声明新的枚举类型。以下是枚举声明的示例。
// The name of enumeration is "flag" and the constant
// are the values of the flag. By default, the values
// of the constants are as follows:
// constant1 = 0, constant2 = 1, constant3 = 2 and
// so on.
enum flag{constant1, constant2, constant3, ....... };
还可以定义enum类型的变量。可以通过两种方式定义它们:
// In both of the below cases, "day" is
// defined as the variable of type week.
enum week{Mon, Tue, Wed};
enum week day;
// Or
enum week{Mon, Tue, Wed}day;
// An example program to demonstrate working
// of enum in C
#include
enum week{Mon, Tue, Wed, Thur, Fri, Sat, Sun};
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}
输出:
2
在上面的示例中,我们声明了“ day”作为变量,并且“ Wed”的值分配给了day,即2。因此,结果是打印了2。
枚举的另一个示例是:
// Another example program to demonstrate working
// of enum in C
#include
enum year{Jan, Feb, Mar, Apr, May, Jun, Jul,
Aug, Sep, Oct, Nov, Dec};
int main()
{
int i;
for (i=Jan; i<=Dec; i++)
printf("%d ", i);
return 0;
}
输出:
0 1 2 3 4 5 6 7 8 9 10 11
在此示例中,for循环将从i = 0运行到i = 11,因为最初i的值为Jan,即Jan,其值为0,Dec的值为11。
有关枚举初始化的有趣事实。
1.两个枚举名称可以具有相同的值。例如,在下面的C程序中,“失败”和“冻结”具有相同的值0。
#include
enum State {Working = 1, Failed = 0, Freezed = 0};
int main()
{
printf("%d, %d, %d", Working, Failed, Freezed);
return 0;
}
输出:
1, 0, 0
2.如果我们没有为枚举名称显式分配值,则默认情况下,编译器会分配从0开始的值。例如,在以下C程序中,sunday的值为0,monday的值为1,依此类推。
#include
enum day {sunday, monday, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum day d = thursday;
printf("The day number stored in d is %d", d);
return 0;
}
输出:
The day number stored in d is 4
3.我们可以按任何顺序将值分配给某个名称。所有未分配的名称都将值作为前一个名称的值加一个。
#include
enum day {sunday = 1, monday, tuesday = 5,
wednesday, thursday = 10, friday, saturday};
int main()
{
printf("%d %d %d %d %d %d %d", sunday, monday, tuesday,
wednesday, thursday, friday, saturday);
return 0;
}
输出:
1 2 5 6 10 11 12
4.分配给枚举名称的值必须是某个整数常量,即该值必须在从最小可能的整数值到最大可能的整数值的范围内。
5.所有枚举常量的范围必须唯一。例如,以下程序编译失败。
enum state {working, failed};
enum result {failed, passed};
int main() { return 0; }
输出:
Compile Error: 'failed' has a previous declaration as 'state failed'
锻炼:
预测以下C程序的输出
程序1:
#include
enum day {sunday = 1, tuesday, wednesday, thursday, friday, saturday};
int main()
{
enum day d = thursday;
printf("The day number stored in d is %d", d);
return 0;
}
程式2:
#include
enum State {WORKING = 0, FAILED, FREEZED};
enum State currState = 2;
enum State FindState() {
return currState;
}
int main() {
(FindState() == WORKING)? printf("WORKING"): printf("NOT WORKING");
return 0;
}
枚举vs宏
我们还可以使用宏来定义名称常量。例如,我们可以使用以下宏定义“工作”和“失败”。
#define Working 0
#define Failed 1
#define Freezed 2
当许多相关的命名常量具有整数值时,使用enum而不是宏有多个优点。
a)枚举遵循作用域规则。
b)枚举变量是自动分配的值。以下更简单
enum state {Working, Failed, Freezed};