initialization of enum array in c++

26,111

Solution 1

Every enumeration has an underlying type, and supports a range of values. The underlying type is an integer type big enough to store the whole range of values. All integers in that range are valid values (see below) for an object of the enumeration type, even if there's no enumerator with that value. 0 is in the range of values of any enumeration, hence initializing an object of enumeration type with 0 is fine.

Integer values can be converted to the type of the enumeration if they are in the range of values that this enumeration supports.

If you initialize an aggregate (like an array) with braces {..} and provide less initializers than there are elements in the aggregate, the resulting elements will be value-initialized. For fundamental types (like int) and enumeration types, this means they will be initialized from the integer 0, converted to their respective type.

move array[6] {FORWARD, BACKWARD, STOP, STOP, STOP};
// equivalent to:
move array[6] {FORWARD, BACKWARD, STOP, STOP, STOP, static_cast<move>(0)};

Solution 2

According to the C++ Standard enumerations with a non-fixed underlaying type have minimum value equal to zero if they were defined such a way that their enumerator with minimum value is not negative.

In your code the enumerator with minimum value is FORWARD. Its value is not negative. So the minimum valid value of the enumeration is 0.

Take into account that according to the same C++ Stsandard

It is possible to define an enumeration that has values not defined by any of its enumerators.

As for the array as it has less initializers than there are elements in the array then all elements that have no an initializer will be zero-initialized. And zero is the valid value for the enumeration.

Share:
26,111
ddur
Author by

ddur

Updated on July 09, 2022

Comments

  • ddur
    ddur almost 2 years

    I'm learning c++ and doing some exercise from a book right now. I'm asked to write definition of enum which takes 3 values (forward, backward, stop) and array of 15 elements of this type. In this definition I have to set values of first 5 elements of this array. I did it without problems, but it made me think.. If I write:

    enum move {FORWARD = 1, BACKWARD, STOP};
    move array[15] {FORWARD, BACKWARD, STOP, STOP, STOP};
    

    ... first 5 elements will have values of 1, 2, 3, 3, 3 but all after that will have 0. How is it possible since "move" can't take values other than 1, 2 or 3? Why is the rest of array initialized anyway if I specified just first 5 fields? Or maybe it just means those are empty fields?

    Please explain in simple way so beginner like me can understand :), thanks.