Getting started with Enumeration type (enum) in C/C ++

Source: Internet
Author: User

If a variable requires several possible values, it can be defined as an enumeration type. The reason for enumeration is to enumerate the possible values of variables or objects.

For example, to make everyone better understand that there is a pen in a pencil, but you don't know what it is before you open it, it may be a pencil or a pen. There are two possibilities, so you can define an enumeration type to represent it!

Enum box {penpencil, pen}; // here you define a variable of Enumeration type called box, the enumerated variable contains two elements, the pencil and pen, respectively.


Here, if you want to define two variables with the same Enumeration type, you can use the following two methods to define them!

Enum box {penpencil, pen };

Enum box box2; // or abbreviated to box box2;


Another way is to define the statement at the same time.

Enum {penpencil, pen} box, box2; // define the statement at the same time!


The enumeration Element System in enumeration variables is processed according to constants.Enumerated constantThey cannot assign values to ordinary arithmetic tasks. Writing and sending such a statement is incorrect, but you can assign values when declaring it!

Enum box {penpencil = 1, pen = 2 };


However, if you do not assign values to elements, the system automatically increments the values from 0, if you only define the first element, the system adds 1 to the value of the previous element to the next element. For example

Enum box {penpencil = 3, pen}; // here pen is 4. The system will automatically assign values to pen = 4!

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.