Enumerations in c ++ (enum)

c++ enumeration, перечисления c  , enumeration c++, enum c++

Enumerations (enum) used to create a C ++ constants. Suppose it is necessary to declare constants for each of musical notes and initialize the appropriate serial number. You can use the familiar us way:

c++ enumeration, перечисления c  , enumeration c++, enum c++

This declaration takes a lot of lines of code and is not convenient. Using enumeration, you can define these constants otherwise. Syntax enum similar to the syntax structures: keyword – descriptor – elements in braces, separated by commas :

c++ enumeration, перечисления c  , enumeration c++, enum c++

This is the full form – with a descriptor (the name of the enumeration). As in the case with structures, the name of an enumeration, you can not use:

c++ enumeration, перечисления c  , enumeration c++, enum c++

In the first case – We can create variables of type enum notes. In the second case, – no.

Note, that the value 1 was given only to the first enumeration member. By default, the first item in the braces are assigned a value 0, the second one more than (1), the third one more second (2) etc. But if you explicitly set the value, as in the example, the increase in the unit will begin with this number. We will show on the screen the values ​​of some elements of the enumeration.

In the console appears:c++ enumeration, перечисления c  , enumeration c++, enum c++

Although we have not explicitly been assigned a value RE and SOL – they keep the correct serial numbers of notes.

The names of enumerators (enumeration members) must be unique. The values ​​may also be the same:

Value 1 will keep KLICHKO_VITALIY and KLICHKO_VLADIMIR. 2 written in CHISORA, 3 – in ADAMEK . In the enumeration elements can only be written to integers. Change in the program following values, are assigned to the elements in curly brackets can not be. If you create a variable of type enum – it can only take the value of one of its elements:

c++ enumeration, перечисления c  , enumeration c++, enum c++

The picture shows, that record number in a variable of type champions is not possible. You can only record a named constant, which is declared at the time of determination enum.

For example, consider fixing. In it create a transfer levelsName. It will contain six elements – “name” floors. User offer “go for a drive” on the elevator.

We declare an integer variable floor in string 10 and initialize it named constant parking. So floor will value 0. In string 13 enter in a while loop. As long as the user enters into a variable exitOrNot value 0, the program will offer him “ride the elevator” – select the number of the floor. After each selection floors alarm sounds (three short beeps) and displays the floor number, and information about, that is placed on it. This is done selection switch statement. His blocks case sorted enumerationg elements. That is, the user enters an integer, and case looking for, any of the elements of the enumeration it corresponds. For example, if introduced 5 – this corresponds to an element Restaurant – displays a message.


c++ enumeration, перечисления c  , enumeration c++, enum c++

Watch a short video about C++ enumerations. It is in English, but to understand it easily, after reading the article:

To support our site – click on the piggy bank and choose any convenient way.

Newsletter of programming:

Enumerations in c ++ (enum)
5 (100%) 5 votes

6 thoughts on “Enumerations in c ++ (enum)

  1. Normal examples, and I did not read the article.

    I formulate, as you please straighten, if Article I broke up in something.

    1) Magic numbers – This is bad, to get rid of them using constant.

    2) constants – it's good, but the constants are strongly connected with each other.

    Example: the program we have a unit. A unit can be a magician, goblin or elf. One embodiment of this might be something:

    const int Mag = 1;
    const int Goblin = 2;
    const int Elf = 3;

    struct Unit {
    string name;
    int unit_type;

    obviously, This is bad, because:
    2.1) constant Mag, Goblin, Elf available to all, i.e.. pollute the namespace;
    2.2) constants can be randomly used in the wrong context, because they are not grouped, i.e.. It is no different from other constants;
    2.3) unit_type field, you can assign the wrong value (the compiler does not tell us about an error) :
    unit.unit_type = -123;
    2.4) We need to invent themselves values ​​of constants and monitor so that they do not recur.

    All these problems erotic decides enum:

    enum UnitType { Mag, Goblin, Elf };
    struct Unit {
    unit_type type;
    string name;

    refer to the constants we can both directly (Mag) and enumeration named (UNITTYPE::Mag). The second option is clearly the context indicates, but it seems to appear in C ++ 11 (earlier it maintained most compilers, but standard like as it is not consistent with).

    unit.unit_type = 123;
    will fail at compile time (i.e.. too early). And if you uzing modern IDE – the earlier (IDE will underline error).

    Well, the values ​​assigned to them automatically, follow this is not necessary.

    The code can be made a bit prettier:
    struct Unit {
    unum Type {Mag, Goblin, Elf} type;
    string name;

    This may be better, tk. it is seen, that Unit and Type inextricably linked (before we encode it in the name UnitType). Encode something in the name is not very good, for example if the Unit be renamed the Item – we would have to rename ItemType, or a bond would not obvious.
    Unit::Type::Mag succinctly sets the context, wherein the constant can be used.

  2. My version of solving the problem of Example:
    pre class=”only:c++ decode:true ”

    using namespace std;

    int main()
    setlocale(LC_ALL, “rus”);
    enum lewels {undParking = -1, oneFloor = 1, secondFloor = 2, Restaurant = 3, Penthouse = 4};
    int lift = 0;
    int exit = 1;
    cout <<"Вы зашли в здание и сейчас находитесь на " << oneFloor << " этаже \n";
    cout <> lift;
    switch (lift)
    cout << "Вы попали в подземную автостоянку \n";
    cout << "Вы на первом этаже \n";
    cout <> exit;
    if (exit == 0)
    cout << "Вы вышли из здания \n";
    cout << "Вы на втором этаже \n";
    cout << "Вы в ресторане \n";
    cout << "Вы в пентхаусе \n";
    cout << "Нет такого этажа \n";
    } while (exit == 1);
    return 0;


    1. A quote from the description of the C and C ++ languages:
      > The S89 version is defined 32 keywords.
      > …
      > enum - User-defined data type “enumerated type”
      > …
      > In C ++ contains all keywords, defined in the S89 version, as well as the following.

      Where is the difference here?

Leave a Reply

Your email address will not be published. Required fields are marked *