C++ enumeration type | enumeration type

C++ enumeration type

In C++, if a variable has only several possible values, it can be defined as an enumerated type. Enumeration refers to listing the values ​​of variables one by one, and the values ​​of variables can only be within the range of the listed values.

C++ declares that enumeration types start with enum.

enum weekday_enum
{
    
    
  Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
};

The above declares an enumeration type weekday, in the curly brackets Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday are called enumeration elements or enumeration constants, indicating that the value of this type of variable can only be one of the above 7 values One, they are user-defined identifiers.

C++ declares the general form of enumeration type as

enum enumeration type name {enumeration constant table column};

After C++ declares the enumeration type, you can use the declared enumeration to define variables.

weekday workday,week_end;

workday和week_end被定义为枚举类型weekday的变量。 

Readers who have studied the C language should know that the name of the enumeration type includes the keyword enum, but it is not allowed to write enum in C++, and enum is generally not written, but the usage of the C language is retained.

About C++ enumeration, the reader needs to know the following six points:

C++ treats enumeration elements as constants, so they are called enumeration constants.
C++ enumeration elements are used as constants and they have values.
C++ compiler assigns them as 0,1,2,3,... in the order of definition.
C++ can specify the value of the enumeration element separately when declaring the enumeration type.
C++ enumeration values ​​can be used for judgment and comparison.
An integer cannot be directly assigned to an enumeration variable in C++.

C++ enumeration type
More cases can be public account: C language entry to proficient

Guess you like

Origin blog.csdn.net/weixin_48669767/article/details/112276681