0

Is is possible to make any assumption on the integral values of an enum class defined like this?

enum class
{
    ZERO, ONE, TWO
};
nyarlathotep108
  • 5,275
  • 2
  • 26
  • 64
  • I believe they are zero indexed and incremental, but I would not make any assumptions. The implementation may be compiler specific. – h0r53 Oct 17 '19 at 15:09
  • @GuillaumeRacicot the question you linked is about `enum` and not `enum class`, I do not think this question is a duplicate of that one – nyarlathotep108 Oct 17 '19 at 15:11
  • 1
    @nyarlathotep108 I think the duplicate still applies since `enum class` is still an enumeration declaration, and the quoted paragraph from the standard applies to any enumeration declaration, including enum, enum class and enum struct. – Guillaume Racicot Oct 17 '19 at 15:13
  • 1
    @nyarlathotep108 The rules for default values for both scoped and unscoped enums are defined by the same passage. [Link](https://timsong-cpp.github.io/cppwp/dcl.enum#2) Edit : It looks like this linked passage is the same as the one quoted in the duplicate's answer. – François Andrieux Oct 17 '19 at 15:13
  • 2
    @CaitLANJenner While you are incorrect in this instance, you are right that it's best to be skeptical in general in c++ and assume things are unsafe or undefined until you know otherwise. – François Andrieux Oct 17 '19 at 15:15
  • @GuillaumeRacicot Looks more it is a duplicate answer than a duplicate question. The fact that in the standard is defined in the same paragraph is part of the answer. – nyarlathotep108 Oct 17 '19 at 15:21
  • The spec says if the first enumerator is not initialized then it starts at zero. What is incorrect about my comment? – h0r53 Oct 17 '19 at 15:21
  • @CaitLANJenner the value of the first enumeration is not implementation defined or compiler specific. It it required by the standard to start at 0. – Guillaume Racicot Oct 17 '19 at 15:26
  • 1
    @nyarlathotep108 I think the rule for duplicates still applies here. Also, the question is very similar, down to the identifiers of the enum. The very fact that this question link to the other is also a good hint for future readers that both behave the same, and should point the future readers to a excellent answer. This is what I think will benefit most readers, beginners and experts. – Guillaume Racicot Oct 17 '19 at 15:30

1 Answers1

2

Yes.

Each enumerator is associated with a value of the underlying type. When initializers are provided in the enumerator-list, the values of enumerators are defined by those initializers. If the first enumerator does not have an initializer, the associated value is zero. For any other enumerator whose definition does not have an initializer, the associated value is the value of the previous enumerator plus one.

From https://en.cppreference.com/w/cpp/language/enum

Max Vollmer
  • 8,412
  • 9
  • 28
  • 43