Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 231
zildjohn01 Avatar asked Mar 04 '09 04:03

zildjohn01


2 Answers

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.

like image 139
Johannes Schaub - litb Avatar answered Sep 21 '22 21:09

Johannes Schaub - litb


Your actual question; why enum/const is the same in D as in C++; seems to be unanswered. Sadly there exists no good reason for this choice whatsoever. I believe that this was just an unintentional side effect in C++ that became a de facto pattern. In D the same pattern was needed, and Walter Bright decided that it should be done as in C++ such that those coming from that place would recognize what to do ... In fact, before this rather IMHO silly decision, the keyword manifest was used instead of enum for this usecase.

like image 39
larsivi Avatar answered Sep 23 '22 21:09

larsivi