Reputation: 2765
enum class Status: char {
test1 = '1',
test2 = '10',
test3
};
int main() {
Status test1 = Status::test1;
Status test2 = Status::test2;
Status test3 = Status::test3;
if (test1==test3) {
cout << "Enum same"<< endl;
}
if (static_cast<char>(test1) == static_cast<char>(test3)) {
cout << "value same" << endl;
}
}
This snippet actually outputs,
Enum same
value same
That means if I mixed enum class
member with set and unset, the compiler does not try to avoid giving the same value as other member? Apart from give a value to each member, any other way to ensure each member in enum class
has different value?
Upvotes: 0
Views: 70
Reputation: 36379
Due to the use of a multi character constant your code is probably (based on the observed behaviour, there is no guarantee that this will always be the case) equivalent to:
enum class Status: char {
test1 = '1',
test2 = '0',
test3
};
As the value of test3
is not specified the compiler simply sets it to 1 more than the previous value, in this case it'll use '1'
. There is no guarantee that enum elements with unspecified values will have a unique value.
See the documentation for more details.
Upvotes: 1