The difference between enumeration and define

Source: Internet
Author: User

1. Brief example of enum enum use
When writing a program, we often need to associate an optional set of alternative properties for an object. For example, the students ' grades a,b,c,d and so on, the weather is sunny, cloudy, rainy and so on.
More commonly, opening a file may have three statuses: input, output, and append. A typical practice is to define 3 constants, namely:
const int input = 1;
const int output = 2;
const int append = 3;
Then, call the following function:
BOOL Open_file (string file_name, int open_mode);
Like what
Open_file ("Phenix_and_the_crane", append);
This is a simple practice, but there are many drawbacks, the main point is that you cannot limit the range of values passed to the 2nd parameter of the Open_file function, as long as the value of the int type is passed as valid. (Of course, the response in this case is to judge the value of the second parameter within the Open_file function, only within the range of the three-way process.) )
The use of enumerations can alleviate this embarrassment to some extent (note 1), which not only implements functions similar to the three constants previously defined, but also combines these three values into a unique group. For example:
Enum Open_modes {input = 1, output, append};
The above defines open_modes as the enumeration type enumeration type. Each named enumeration is a unique type and is a type specifier. For example, we can re-write a open_file function:
BOOL Open_file (string file_name, open_modes om);
In the Open_modes enumeration, input, output, append, are called enumeration sub-enumerator, which define the range of values for the objects defined by Open_modes. At this point, the call to the Open_file function is identical to the previous method:
Open_file ("Phenix_and_the_crane", append);
However, if the second argument passed to Open_file is not the value of the Open_modes enumeration type (note 1), then the compiler will recognize the error, even if the value of the parameter is equivalent to input, output, one of the Append,
The same can be wrong oh! For example:
Open_file ("Phenix_and_the_crane", 1);
2. Definition of enumerations
An enumeration is a type that can hold a set of values that are depicted by the user. Definitions, enumerations are used much like an integer type.
The definition of an enumeration has the following form, which begins with the keyword enum, followed by an optional enumeration name, and the curly brace {} contains a comma-delimited list of enumerated enumerators lists:
Enum [enumeration name] {enumerator1[=value1], enumerator2[=value2], ...};
3. Enum Subtype and value
The type of the enumerator is the one in which it is located, for example, in the Open_modes enumeration mentioned earlier, the types of enumerations such as Input,output and append are open_modes. This is done in order to give the user and compiler some hints about the intended use of the variable.
By default, the first enumerator is assigned a value of 0, and the next enumeration sub-value is the value of the previous enumerator +1, for example:
Enum Weather {Sunny, cloudy, rainy, windy};
which
Sunny = = 0,
Cloudy = = 1,
Rainy = = 2,
Windy = = 3;
This is the default, and sometimes we want to explicitly specify the value of an enumerator, what happens? Look:
Enum Some_fruit {apple = 3, orange, banana = 4, bear};
Okay, Apple = = 3, banana = = 4; What about orange and bear? Remember the preceding sentence, the default is "the next enumerator is the value of the previous enumerator +1". Since these two enumerators do not have an explicit assignment, they do so according to the default rules, so orange = = 4, bear = = 5.
As you can see from this example, the values of the enumerators in the same enumeration do not need to be unique. What is the use of this? Here's a simple example:
Enum Some_big_cities {
Guangzhou = 4,
Shenzhen = 4,
Hongkong = 4,
Shanghai = 2,
BEIJING = 3,
Chongqi = 3
};
The above simply by area, the five cities according to South China (4), East China (2), North China (3) several cities classified.
4. Definition, initialization and assignment of enumeration variables
Since each enumeration is a type, it is natural for the type to declare the variable, for example, by the Some_big_cities defined earlier:
Some_big_cities where_i_am;
It is important to note that there is no initialization when declaring where_i_am, if you print the value of where_i_am at this point:
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 you declare WH to be a global variable, the other case:
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 results are obtained in Visual C + + 2005 Express and do not know what the other compilers are doing, or why they are getting such results. Come down and look for information.
When you define an enumeration variable, you can initialize it, for example:
Some_big_cities wh = Guangzhou;
Note that only one of the enumerators can be taken to the right of the equal sign; In particular, for example, Guangzhou, although guangzhou==4, the following initialization is an error:
Some_big_cities WH = 4;
Visual C + + 2005 Compiler tips:
Error C2440: ' Initializing ': cannot convert from ' int ' to ' some_big_cities '
It can be seen that an integer type cannot be assigned to an enumeration variable directly, because enumerations and integers are of different types unless explicitly converted. The relationship between enumerations and integral types is later.
In addition to initialization, enumeration 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. Range of enumeration values
If the values of all the enumerators in an enumeration are non-negative, the representation range of the enumeration is [0:2^k-1], where 2^k is the power of the smallest 2 that enables all the enumerators to be in this range, and if there is a negative enumeration value, the range of values for that enumeration is [ -2^k,2^k-1]. For example:
Enum E1 {dark, light}; Range 0:1
Enum E3 {min = -10, max = 1000}; Range -1024:1023
6. The relationship between enumeration and integral type
An integer value can only be explicitly converted to an enumeration value, but the result is undefined if the result of the conversion is outside the range of the enumeration value.
Enum e1 {dark = 1, light = 10};
E1 VAR1 = E1 (50); No definition
E1 VAR2 = E1 (3); Compiled by
It is also explained here that the reason for not allowing implicit conversion from an integral type to an enumeration is not allowed because most of the integer values do not have a corresponding representation in a particular enumeration.
As an example of an enumeration that can be used as a specific integer number, it can be realized from open_modes.
7. Custom Operators
An enumeration is a user-defined type, so the user can define its own actions for it, such as + + or <<. However, it is not possible to use the enumeration as an integral type until it is undefined, 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, and the following error is obtained under Visual C + + 6 compilation:
Error c2675:unary ' + + ': ' enum main::somecities ' does not define this operator or a conversion to a type acceptable to th E predefined operator

8. Sizeof
A sizeof of an enumerated type is a sizeof of an integral type that can hold its scope, and is not greater than sizeof (int), unless the value of an enumerator cannot be represented by an int or unsigned int.
In a 32-bit machine, sizeof (int) is generally equal to 4. All the enumerations described earlier, for example,
Enum Somecities
{
Zhanjiang,
Maoming,
Yangjiang,
Jiangmen,
Zhongshan
};

calculates its sizeof, which may be 1 or 4. In my Intel E2160 dual-core, 32-bit machine, I get 4.
-----------------------------------------------------------------------------------
[Note 1, Begin]
Since it is possible to get the value of the corresponding enumeration type by explicitly converting an integer, it is not enough to declare an enumeration to limit the range of parameters that are passed to the function, and 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); Assigns a value of 50 to onecity by an explicit conversion
Printenum (onecity); Get 50 Output under VC + + 6 Compiler
return 0;
}

The above example shows that although there is no enumeration value assigned to 50 in the definition of somecities, because 50 is within the value range of the enumeration, it is successfully passed to the Printenum function by explicitly declaring a defined enumeration value.

Enumeration and define summary:

1. Enumeration members can be not unique, two enumeration members can have the same value; Cannot change the value of an enumeration member, which is a constant expression that can be used anywhere a constant expression is required.

2. Initialization or assignment of an enumeration type object can only be done by its enumeration members or by other objects of the same enumeration type

3.enum enumeration values are constants, #define宏值不是常量

The 4.enum enumeration has a type, #define宏没有类型. An enumeration variable has the same properties as a normal variable, such as scope, value, and so on, but the macro does not, and the macro is not part of the language, which is a preprocessing substitution. Therefore, enumerations can be used with enumerations as much as possible.

5. Macros do not have scope, the macro can use this macro after the definition of the code. Macros can be defined repeatedly, which may cause the values of the macro to be modified, so do not use macros to define integer variables, and it is recommended to use enumerations or const

The difference between enumeration and define

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.