Search code examples
optimizationenumsconstantsd

const vs enum in D


Check out this quote from here, towards the bottom of the page. (I believe the quoted comment about consts apply to invariants as well)

Enumerations differ from consts in that they do not consume any space in the final outputted object/library/executable, whereas consts do.

So apparently value1 will bloat the executable, while value2 is treated as a literal and doesn't appear in the object file.

const int value1 = 0xBAD;
enum int value2 = 42;

Back in C++ I always assumed this was for legacy reasons, and old compilers that couldn't optimize away constants. But if this is still true in D, there must be a deeper reason behind this. Anyone know why?


Solution

  • Just like in C++, an enum in D seems to be a "conserved integer literal" (edit: amazing, D2 even supports floats and strings). Its enumerators have no location. They are just immaterial as values without identity.

    Placing enum is new in D2. It first defines a new variable. It is not an lvalue (so you also cannot take its address). An

    enum int a = 10; // new in D2
    

    Is like

    enum : int { a = 10 }
    

    If i can trust my poor D knowledge. So, a in here is not an lvalue (no location and you can't take its address). A const, however, has an address. If you have a global (not sure whether this is the right D terminology) const variable, the compiler usually can't optimize it away, because it doesn't know what modules can access that variable or could take its address. So it has to allocate storage for it.

    I think if you have a local const, the compiler can still optimize it away just as in C++, because the compiler knows by looking at its scope whether or not anyone is interested in its address or whether everyone just takes its value.