The basics of programming in c++ for beginners

Enumerations in c ++ (enum)

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 enumnotes. 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 keepKLICHKO_VITALIY andKLICHKO_VLADIMIR. 2 written inCHISORA, 3 – inADAMEK . 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 transferlevelsName. 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 constantparking. So floor will value 0. In string 13 enter in a while loop. As long as the user enters into a variableexitOrNot 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 blockscase sorted enumerationg elements. That is, the user enters an integer, andcase  looking for, any of the elements of the enumeration it corresponds.

For example, if introduced 5 –  this corresponds to an elementRestaurant – displays a message.

Result:

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

Watch a short video on the transfers C ++.

8 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 ”

    #include
    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";
    do
    {
    cout <> lift;
    switch (lift)
    {
    case(undParking):
    cout << "Вы попали в подземную автостоянку \n";
    break;
    case(oneFloor):
    cout << "Вы на первом этаже \n";
    cout <> exit;
    if (exit == 0)
    {
    cout << "Вы вышли из здания \n";
    }
    break;
    case(secondFloor):
    cout << "Вы на втором этаже \n";
    break;
    case(Restaurant):
    cout << "Вы в ресторане \n";
    break;
    case(Penthouse):
    cout << "Вы в пентхаусе \n";
    break;
    default:
    cout << "Нет такого этажа \n";
    }
    } while (exit == 1);
    return 0;
    }

    /pre

    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?

  3. If for each enumeration case the value is set (known as "raw" value), this value can be a string, a character or value of any integer or floating point type.

  4. You got a transaction from unknown user. Withdrаw > https://telegra.ph/Ticket--9515-12-16?hs=39f81abfecea98d2ee16a4a5737d3fb8& says:

    3da1mt

Leave a Reply

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