0

Duplicate enum values

Is it allowed to have duplicate enum values in c?

18th Nov 2018, 12:18 PM
Akshay Kumbhar
Akshay Kumbhar - avatar
5 ответов
+ 5
Akshay I think you answered your own question: Yes (duh, or it wouldn't run). What's an enum? A numeric constant. The purpose? Believe it or not laziness. WTF? Okay, not 100%, there's other purposes like abstraction (eyup), but it boils down to this: enum pee {A=10, B, C, D}; Is shorthand for: const int A=10, B=11, C=12, D=13; Which is clever since our compiler generates the consts declarations. Now you understand _what_ it is, you understand _why_ the code runs; Valen.H. ~ it works because two constants _can_ share a value: const int X = 10; const int Y = 10; No problem. In the lifespan of the code, Y may need to be changed to 11, but for now it's 10. Why not #define X 10 then? First, the preprocessor substitutes _all_ occurrences of X so you may get mangled code, second, they become literal 10 _before_ compilation. These caveats are a topic unto themselves. Bottom line: Nothing wrong, not a hack, not a language flaw.
18th Nov 2018, 10:59 PM
non
+ 9
I don't think its possible in any language. Why would someone want that?
18th Nov 2018, 12:22 PM
Valen.H. ~
Valen.H. ~ - avatar
+ 4
enum test_1 { ZERO, ONE, TWO, // TWO (Error for redeclaration) }; // But enum test_2 { ZERO = 0, ONE = 1, TWO = 2, THREE = 2, // A-OK for their values };
18th Nov 2018, 12:34 PM
Babak
Babak - avatar
+ 4
A=3, B=2, C After the last explicit assignment (B = 2), the enum's internal will continue to assign values incrementally (3, 4, 5, ...).
18th Nov 2018, 12:38 PM
Babak
Babak - avatar
0
Valen.H. ~ please go through this code you will get idea what i am actually asking. https://code.sololearn.com/c1yj6W3xG8Cb/?ref=app
18th Nov 2018, 12:34 PM
Akshay Kumbhar
Akshay Kumbhar - avatar