0

See the following code:

enum ChunkIndex {
  ZeroIndex = 0,
  SpecializedIndex = ZeroIndex,
  SmallIndex = SpecializedIndex + 1,
  MediumIndex = SmallIndex + 1,
  HumongousIndex = MediumIndex + 1,
  NumberOfFreeLists = 3,
  NumberOfInUseLists = 4
};
ChunkIndex index0 = (ChunkIndex) (0);
ChunkIndex index3 = (ChunkIndex) (3);
ChunkIndex index4 = (ChunkIndex) (4);

You see that there exists at least two enum values that equal to 0.

The same as 3.

What will happen when cast 0 to enum ChunkIndex?

The same question with 3.

The code above is from jdk8/openjdk/hotspot/src/share/vm/memory/metaspace.cpp line 83 and its above 7 lines.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
yangyixiaof
  • 225
  • 4
  • 15
  • You have the code. So what happened when you compiled it? – Kai Mattern Sep 20 '14 at 08:54
  • Nothing will happen - the enum symbols are just syntactic sugar for replacing integer values with something more meaningful. If your debugger understands enums then it will be free to pick any label which matches the integer value. – Paul R Sep 20 '14 at 08:54
  • Why is this tagged both java and C++? This is specifically java although it might apply to C++ as well – Marco A. Sep 20 '14 at 08:56
  • @MarcoA.: it seems to be from a C++ source file that's part of a JDK ? – Paul R Sep 20 '14 at 08:57
  • @PaulR oh my bad you're right. I'll re-add the tag – Marco A. Sep 20 '14 at 08:57
  • 1
    Also the question was already asked multiple times: http://stackoverflow.com/questions/8043027/non-unique-enum-values – Kai Mattern Sep 20 '14 at 08:57
  • 2
    I would have marked it a duplicate of a C++ question, that is C# and although it works the same it might not be obvious to a reader. I'll leave my answer below to clarify this. – Marco A. Sep 20 '14 at 09:05
  • @MarcoA - I've removed the "java" tag again. The fact that the code comes from the Java source code is not *relevant* to the Question. Adding a "java" tag is unhelpful for people who are using tags properly; e.g. to improve search precision, or decide what questions to try to answer. – Stephen C Sep 20 '14 at 09:07

1 Answers1

2

[Strictly regarding C++]

You're going to have that 0-converted-to-enum value matching both the 0 values of the enum

ChunkIndex index0 = (ChunkIndex) (0);
if(index0 == ChunkIndex::ZeroIndex)
    cout << "hello"; // Gets printed
if(index0 == ChunkIndex::SpecializedIndex)
    cout << "world"; // Gets printed

This is also valid with C++11 typesafe enums

enum class ChunkIndex

As PaulR noted, enums are usually syntactic sugar to render integer values (whatever their value is) more meaningful to readers.

Community
  • 1
  • 1
Marco A.
  • 43,032
  • 26
  • 132
  • 246