Enumeration usage is summarized in detail

  • 2020-06-03 08:08:13
  • OfStack

1, enumerate enum use of a shallow example
When writing a program, we often need to associate a set of optional alternative attributes for an object. For example, students' grades are divided into A,B,C,D, etc., and the weather is divided into sunny, cloudy, rainy, etc.
More commonly, a file can be opened in three states: input, output, and append. Typically, three constants are defined, that is:
const int input = 1;
const int output = 2;
const int append = 3;
Then, call the following functions:
bool open_file(string file_name, int open_mode);
For instance,
open_file("Phenix_and_the_Crane", append);
This approach is relatively simple, but it has a number of drawbacks, the main one being the inability to limit the range of the second argument passed to the open_file function, which is legal as long as a value of type int is passed. (In this case, of course, the response is to determine the value of the second parameter inside the open_file function, only in the range of 1, 2, and 3.)
The use of enumerations alleviates this awkwardness to a certain extent by not only implementing functions similar to those previously defined for the three constants, but also combining the three values into a single group with no two. Such as:
enum open_modes {input = 1, output, append};
Above, open_modes is defined as the enumeration type enumeration type. Each named enumeration is of a unique type, a type identifier type specifier. For example, we could rewrite an open_file function:
bool open_file(string file_name, open_modes om);
In the open_modes enumeration, input, output and append are called enumerators enumerator, which limit the value range of objects defined by open_modes. At this point, the call to the open_file function and the previous method are still 1 module 1:
open_file("Phenix_and_the_Crane", append);
However, if the second parameter passed to open_file is not an open_modes enumerated type value (note 1), the compiler will recognize the error. Even if the value of this parameter is equivalent to one of input, output, append, one will make an error! Such as:
open_file("Phenix_and_the_Crane", 1);

2. Definition of enumeration
An enumeration is a type that can hold a set of user-defined values. Enumerations are used much like 1 integer type.
The definition of an enumeration takes the form of starting with the keyword enum, followed by an optional enumeration name, followed by a comma separated enumeration sublist with curly braces {} containing enumerators list:
enum [enumeration name] {enumerator1[=value1], enumerator2[=value2], ...};

3. Type and value of enumerator
The type of an enumerator is the enumeration in which it is, for example, open_modes, input,output and append are all enumerated by open_modes. The idea is to give the user and compiler 1 hints about the intended use of the variable.
By default, the first enumerator is assigned a value of 0, and the next enumeration is the value +1 of the previous one, for example:
enum weather {sunny, cloudy, rainy, windy};
Among them
sunny == 0,
cloudy == 1,
rainy == 2,
windy == 3;
This is the default, and sometimes we want to explicitly specify the value of an enumerator, so what happens? Take a look at:
enum some_fruit {apple = 3, orange, banana = 4, bear};
Ok, apple == 3, banana == 4; What about orange and bear? Remember the previous statement, by default, "the value of the next enumerator is the value of the previous enumerator +1". Since the two enumerators are not explicitly assigned, the default rule is followed, so orange == 4, bear == 5.

As you can see from this example, the value of an enumerator in the same 1 enumeration does not need to be unique. What's the use of that? Here's a simple example:


enum some_big_cities {
                                               Guangzhou = 4,
                                               Shenzhen    = 4,
                                               Hongkong   = 4,
                                               Shanghai    = 2,
                                               Beijing         = 3,
                                               Chongqi      = 3
                                           };

The above five cities are simply classified by region into several cities in South China (4), East China (2) and North China (3).

4. Definition, initialization and assignment of enumerated variables
Since each enumeration is a type, it is natural to declare variables with that type, for example, some_big_cities as previously defined:
some_big_cities where_I_am;
Note that where_I_am was not initialized when it was declared. If the value of where_I_am is printed then:


enum some_big_cities {
                                            Guangzhou = 4,
                                            Shenzhen = 4,
                                            Hongkong = 4,
                                            Shanghai = 2,
                                            Beijing = 3,
                                            Chongqi = 5};
int main(void)
{
     some_big_cities wh;
     cout<<"the value is: "<<wh<<endl;
     return 0;
}

The output will be the value is: 1. However, if wh is declared as a global variable, another situation occurs:

enum some_big_cities {Guangzhou = 1 Shenzhen = 1, Hongkong = 1,
                                       Shanghai = 2, Beijing = 3, Chongqi = 5};
some_big_cities wh;
int main(void)
{
   cout<<"the value is: "<<wh<<endl;
   return 0;
}

The output will be the value is: 0;

The above results are obtained in Visual C++ 2005 Express, I do not know how other compilers, and I do not know why this result. Come down and look for more information.
When you define an enumeration variable, you can initialize it, for example:
some_big_cities wh = Guangzhou;
Note that you can only take one of the enumerators on the right hand side of the equals sign; In particular, take Guangzhou as an example. Although Guangzhou==4, the following initialization is wrong:
some_big_cities wh = 4;
Visual C++ 2005 Compiler tips:
error C2440: 'initializing' : cannot convert from 'int' to 'some_big_cities'
As you can see, you cannot assign an integer to an enumeration variable directly because enumerations and integers are different types unless explicitly converted. The relationship between enumerations and integers will be discussed later.

In addition to initialization, enumerated variables also have assignment operations:
some_big_cities wh;
wh = Guangzhou;
wh = Shanghai;
or
some_big_cities wh1 = Guangzhou;
some_big_cities wh2 = Shanghai;
wh2 = wh1;


5. Value range of enumeration
If all enumerators in an enumeration have non-negative values, the range of representation of the enumeration is [0:2^ k-1], where 2^k is the smallest power of 2 that makes all enumerators in this range; If there is a negative enumeration value, the value range of the enumeration is [-2^k,2^ ES196en-1]. For example:
enum e1 {dark light}; / / range 1-0
enum e3 {min = -10, max = 1000}; / / range - 1024:1023

6. The relationship between enumeration and integer
An integer value can only be explicitly converted to 1 enumeration value, but if the result of the transformation is outside the enumeration value range, the result is undefined.
enum e1 {dark = 1, light = 10};
e1 VAR1 = e1 (50); / / no definition
e1 VAR2 = e1 (3); // Compiled through
It also explains why implicit conversion from an integer to an enumeration is not allowed, because most integer values have no corresponding representation in a particular enumeration.
As for an example where enumerations can be used as specific integers, see open_modes.

7. Custom operators
Enumerations are user-defined types, so users can define their own operations for them, such as ++ or < < And so on. However, enumerations cannot be used by default because they are like integers until they are defined. For example:


   enum SomeCities
{
   zhanjiang,
   Maoming,
   Yangjiang,
   Jiangmen,
   Zhongshan
};
SomeCities oneCity;
for (oneCity = zhanjiang; oneCity != Zhongshan; ++oneCity)
{
   cout<<oneCity<<endl;
}

The above ++OneCity is undefined. The following error is obtained under the compilation of Visual C++ 6:
error C2675: unary '++' : 'enum main::SomeCities' does not define this operator or a conversion to a type acceptable to the predefined operator

8 Sizeof.
An sizeof of an enumeration type is an sizeof of an integer that can hold its range and is no greater than sizeof(int) unless the value of an enumeration cannot be expressed as int or unsigned int.

In 32-bit machines, sizeof(int)1 generally equals 4. All the enumerations introduced earlier, for example,


enum SomeCities
{
   zhanjiang,
   Maoming,
   Yangjiang,
   Jiangmen,
   Zhongshan
};

So if you calculate the sizeof, it could be 1, it could be 4. On my intel E2160 dual-core, 32-bit machine, I get 4.
-----------------------------------------------------------------------------------
[note 1, Begin]
Since it is possible to get a value of the corresponding enumerated type by explicitly converting an integer, declaring an enumeration to limit the range of parameters passed to a function is not sufficient.
Here is an example:

enum SomeCities
{
zhanjiang=1, //1
Maoming,     //2
Yangjiang,   //3
Jiangmen,   //4
Zhongshan = 1000 //1000
};
void printEnum(SomeCities sc)
{
cout<<sc<<endl;
}
int main(void)
{
SomeCities oneCity = SomeCities(50); // will 50 By explicit conversion, is oneCity The assignment 
printEnum(oneCity); // in VC++ 6  I'm going to get it from the compiler 50 The output 
return 0;
}

The above example shows that although there is no enumeration value assigned to 50 in the definition of SomeCities, since 50 is in the range of the enumeration, one defined enumeration value is successfully passed to the printEnum function by explicitly declaring it.


Related articles: