Apologies in advance as I'm sure someone must have asked this before but I can't find it.
Just had a surprise, a colleague and I both added the same value in for an enum, and it compiled, e.g.
enum MyEnum
{
mine = 1,
his = 1
}
Looks like C/C++ supports this also (?). Any reason for this behaviour, any cases where it's useful? I saw one case with difference human languages (one = 1, eins = 1, etc) but I'm not convinced
Thanks
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
The values assigned to the enum names must be integral constant, i.e., it should not be of other types such string, float, etc. All the enum names must be unique in their scope, i.e., if we define two enum having same scope, then these two enums should have different enum names otherwise compiler will throw an error.
Since there is no problem with a type that contains an multiple constants that have the same value, there is no problem with the enum definition. But since the enum does not have unique values you might have an issue when converting into this enum.
There is currently no way to detect or prevent multiple identical enum values in an enum.
Let's take a simple example
enum PrivilegeLevel
{
None,
Reporter,
Reviewer,
Admin,
DefaultForNewUser = None,
DefaultForProjectOwner = Reviewer,
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With