views:

70

answers:

5

How do enums work 'behind the scenes' in programming languages? I am guessing that each language has a different way of representing these datatypes.

In java you can use the == operator, for example:

public class TestEnum {
   private enum Test {
      foo, bar
   }

   public static void main(String[] args) {
      System.out.println(Test.foo == Test.foo); // returns true
   }
}

Is an enum type converted to a primitive during the ==? Or is the enum value a Singleton? Does C# leverage enums in the same manner as java? Are database enum types treated differently compared to programming languages?

A: 

I think that most languages convert enums into int behind the scenes - although that certainly isn't requirement.

For example - in your example above it is certainly possible that the compiler realizes that the two values are equal without ever converting them to some intermediate representation and just emits a true value.

Aaron
A: 

.Net language represent them in form of integers. If you do

If 1 == foo , this should return true

What I would usually to be easier to understand is this :

public enum Test
    foo = 1
    bar = 2
end enum

Give it a try, change the 1 and 2 with strings. This should throw you a compiler error.

David Brunelle
A: 

I would think enums are simply const integers.

so you have

const int foo = 0;
const int bar = 1;

and so on with the compiler adding the namespace 'Test' to them

Ali
+2  A: 

Java enums make use of a lot of tricks to still be objects but work with ==. The original typesafe enum pattern (see also Effective Java) can provide some insight, but the Enum.java source will show you exactly how they do it now.

Hank Gay
+1  A: 

An enum type in Java is actually a special compiler-generated class rather than an arithmetic type: enum values behave as global pre-generated instances in order to compare references in place of equals.

You can verify it disassembling a .class file:

  Code:
    0:   getstatic       #2; //Field YourEnum.BAR:LYourEnum;
    3:   getstatic       #3; //Field YourEnum.FOO:LYourEnum;
    6:   if_acmpne       17    

it should roughly equivalent to the following Java code:

enum YourEnum {
    FOO,
    BAR
}

// ...
if (YourEnum.BAR == YourEnum.FOO)

For the sake of simplicity you can think it as a special case of string interning.

dfa

related questions