Cprogramming 简明教程

Enumeration (or enum) in C

Enumeration (or enum) in C

C enumeration ( enum ) 是一个枚举数据类型,由一组整数常量组成。当要为整数常量分配用户定义的名称时, Enums 非常有用。 enum 关键字用于定义枚举。

C enumeration (enum) is an enumerated data type that consists of a group of integral constants. Enums are useful when you want to assign user-defined names to integral constants. The enum keyword is used to define enums.

Defining and Declaring an Enum Type

要声明和定义枚举 (enum) 数据类型,请按照枚举名称使用 enum 关键字,并将所有值分配在大括号内。

To declare and define an enumeration (enum) data type, use the enum keyword followed by the enum name and assign all values inside the curly braces.

Syntax

以下是你用于定义枚举类型的语法 −

This is the syntax you would use to define an enum type −

enum enum_name{const1, const2, ... };

Enum Variable Declaration

声明枚举类型后,还可以声明其变量以访问枚举成员(常量)。要声明枚举变量,请按照枚举名称(enum_name)编写 enum 关键字,然后编写变量名称(var)。

After declaring an enumeration type, you can also declare its variable to access enumeration members (constants). To declare an enum variable, write the enum keyword followed by the enaum name (enum_name) and then the variable name (var).

Syntax

以下是声明枚举类型变量的语法 −

Below is the syntax to declare a variable of enum type −

enum enum_name var;

Example

我们使用名称 myenum 定义一个枚举类型 −

Let us define an enum type with the name myenum

enum myenum {val1, val2, val3, val4};

标识符值是无符号整数,并且从 "0" 开始。val1 表示 0,val2 表示 1,依此类推。

Identifier values are unsigned integers and they start from "0". val1 refers 0, val2 refers 1, and so on.

myenum 类型的变量声明如下 −

A variable of myenum type is declared as follows −

enum myenum var;

myenum 类型的可能的常数值在花括号内枚举。

The possible constant values of myenum type are enumerated inside the curly brackets.

Change Enum Constants Values

当声明枚举类型时,默认情况下第一个枚举常量初始化为 0,第二个常量初始化为 1,依此类推。还可以将任意整数值分配给枚举的任何常量。

When we declare an enum type, the first constant of the enum is initialized with 0 by default, the second constant is initialized with 1, and so on. We can also assign any integer value to any constant of enum.

Example

在以下示例中,我们声明一个枚举类型并为枚举常量分配不同的值。

In the following example, we are declaring an enum type and assigning different values to the enum constants.

#include <stdio.h>

enum status_codes { OKAY = 1, CANCEL = 0, ALERT = 2 };

int main() {
   // Printing values
   printf("OKAY = %d\n", OKAY);
   printf("CANCEL = %d\n", CANCEL);
   printf("ALERT = %d\n", ALERT);

   return 0;
}

它将生成如下输出:

It will produce the following output −

OKAY = 1
CANCEL = 0
ALERT = 2

Enum in Switch Statements

C language switch case statement 使用整数值。我们可以使用枚举类型定义常量(带或不带)整数类型值,以便在 switch case 语句中使用它们。

C language switch case statement works with integral values. We can use enum type to define constants with (or, without) integral type values to use them in switch case statements.

Example

在以下示例中,枚举了彩虹中的颜色。

In the following example, the colors in the rainbow are enumerated.

#include <stdio.h>

// Enum declaration
enum colors { VIOLET, INDIGO, BLUE, GREEN, YELLOW, ORANGE, RED };

int main() {
   // Enum variable declaration
   enum colors color = YELLOW;
   // switch statement using enum
   switch (color) {
      case BLUE:
         printf("Blue color");
         break;

      case GREEN:
         printf("Green color");
         break;

      case RED:
         printf("Red color");
         break;

      default:
         printf("Color other than RGB");
   }

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

Color other than RGB

Examples of Enumeration (enum) Type

练习以下示例以了解 C 编程语言中的枚举(或枚举)类型概念。

Practice the following examples to understand the concept of enumeration (or, enum) type in C programming language.

Example 1: Enum Constants Get Incrementing Integer Values

C 为每个常量分配递增的整数值,从 "0" 开始。当将 val2 分配给上面的变量时,

C assigns incrementing integer values to each constant, starting with "0". When we assign val2 to the above variable,

var = val2;

分配给 val2 的整数值为 1。看看以下示例 −

The integer value assigned to val2 is 1. Take a look at the following example −

#include <stdio.h>

enum myenum {val1, val2, val3, val4};

int main(){

   enum myenum var;
   var = val2;
   printf("var = %d", var);

   return 0;
}

它将生成如下输出:

It will produce the following output −

var = 1

Example 2: Enumerating the Weekdays

让我们声明枚举类型 weekdays 以枚举天数的名称并将其值分配给枚举类型变量 −

Let us declare an enum type weekdays to enumerate the names of the days and assign its value to the enum type variable −

#include <stdio.h>

int main(){

   enum weekdays {Sun, Mon, Tue, Wed, Thu, Fri, Sat};

   printf ("Monday = %d\n", Mon);
   printf ("Thursday = %d\n", Thu);
   printf ("Sunday = %d\n", Sun);
}

它将生成如下输出:

It will produce the following output −

Monday = 1
Thursday = 4
Sunday = 0

Example 3: Declaring a Variable of Enum Type

枚举数据类型一个典型应用是将星期分配给整数变量。在这个代码中,我们已经声明了一个类型为 weekdays 的枚举变量 −

A typical application of enumerated data types is to assign weekdays to the integer values. In this code, we have declared a variable of weekdays enum type −

#include <stdio.h>

enum weekdays {Sun, Mon, Tue, Wed, Thu, Fri, Sat};

int main(){

   enum weekdays day;
   day = Wed;
   printf("Day number of Wed is = %d", day);

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

Day number of Wed is = 3

Example 4: Enum Values By Default Start from "0"

在这个代码中,我们为日历年中月份的名字定义了一个枚举类型。默认情况下,C 赋值从 "0" 开始。例如,在下面的 C 程序中,Jan 得到的值是 "0",Feb 得到的值是 "1",以此类推。

In this code, we define an enum type for names of the month in a calendar year. By default, C assigns the values starting from "0". For example, in the following C program, Jan gets the value "0", Feb gets "1", and so on.

#include <stdio.h>

enum months{Jan, Feb, Mar, Apr, May, Jun, Jul,
   Aug, Sep, Oct, Nov, Dec};

int main(){

   for (int i = Jan; i <= Dec; i++)
      printf("Month No: %d\n", i);

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

Month No: 0
Month No: 1
Month No: 2
Month No: 3
Month No: 4
Month No: 5
Month No: 6
Month No: 7
Month No: 8
Month No: 9
Month No: 10
Month No: 11

Example 5: Starting an Enum from 1

要从 1 开始枚举,将 1 明确分配给第一个值,编译器将递增的数字分配给后续的值。

To start enumeration from 1, assign 1 explicitly to the first value, the compiler will assign incrementing numbers to the subsequent values.

#include <stdio.h>

enum months{Jan=1, Feb, Mar, Apr, May, Jun, Jul,
   Aug, Sep, Oct, Nov, Dec};

int main(){

   for (int i = Jan; i <= Dec; i++)
      printf("Month No: %d\n", i);

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

Month No: 1
Month No: 2
Month No: 3
Month No: 4
Month No: 5
Month No: 6
Month No: 7
Month No: 8
Month No: 9
Month No: 10
Month No: 11
Month No: 12

Example 6: Enumerating HTTP Status Codes

枚举类型中的常量不必具有递增的整数值。您可以为每个常量分配一个不同的唯一值,该值可以是任何序列。

It is not necessary that the constants in the enum type should have incremental integer values. You can assign each of the constants a different and unique value, which may be in any sequence.

在下面的代码中,枚举类型枚举 HTTP status codes

In the following code, the enum type enumerates HTTP status codes.

#include <stdio.h>

enum status {
   OK = 200,
   BadRequest = 400,
   Unauthorized = 401,
   Forbidden = 403,
   NotFound = 404,
   InternalServerError = 500,
};

int main(){

   enum status code =  InternalServerError;
   if (code == 500)
   printf("Internal Server Error has been encountered");

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

Internal Server Error has been encountered

Example 7: Assigning a Fixed Number to Enum Constants

您可以为某些常量分配一个固定的整数,让编译器为其他常量分配值。所有未分配的名称都获得一个值,该值是 "前一个名称的值加一"。

You can assign a fixed integer to some of the constants, leaving the compiler to assign values to others. All unassigned names get a value that is "value of previous name plus one".

#include <stdio.h>

enum myenum {a, b = 5, c, d, e = 10, f};

int main(){

   printf("a: %d\n", a);
   printf("b: %d\n", b);
   printf("c: %d\n", c);
   printf("d: %d\n", d);
   printf("e: %d\n", e);
   printf("f: %d\n", f);

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

a: 0
b: 5
c: 6
d: 7
e: 10
f: 11

Applications of Enums

我们可以在 C 中在不同情况下使用枚举,其中一些列在下面 −

We can use enums in C in different cases, some of which are listed below −

  1. To store constant values, for example, weekdays, months, directions, colors, etc.

  2. Enums are used for using flags, status codes, etc.

  3. Enums can be used while using switch-case statements in C.