Enumeration (enumeration)

Source: Internet
Author: User

The enum tool for C + + provides another way to create symbolic constants, which can be substituted for Const. It also allows you to define new types, but you must follow strict restrictions. The syntax for using an enum is similar to the usage structure.

enum Spectrum{red,orange,yellow,green,blue,violet,indigo,ultraviolet};

This statement accomplishes two tasks.

    • Make spectrum the name of the new type; spectrum is called an enumeration , just as a struct variable is called a struct.
    • Red, orange, yellow, etc. are used as symbolic constants and they correspond to integer values 0~7. These constants are called enumerators.

By default, an integer value is assigned to an enumerator, the first enumerator has a value of 0, the second enumerator has a value of 1, and so on. You can override the default value by explicitly specifying an integer value.

You can declare variables of this type through the enumeration name .

Spectrum Band;

Special properties of enumeration variables

In the case of no coercion type conversion, only the enumerator that is used when defining the enumeration can be assigned to variables of this enumeration, as follows:

Band=blue; // valid, Blue is the enumeration amount band=; // invalid, 2000 is not an enumerator

As a result, the spectrum variable is limited to only 8 possible values. If you attempt to assign an illegal value to it, some compilers will have compiler errors, while others issue warnings. For maximum portability, you should assign a non-enum value to an enum variable as an error.

Enumeration (enumeration)

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.