Question

Why does Phobos use enum to define constants? For example, in std.math:

enum real E = 2.7182818284590452354L;

Why not use a global immutable? What are the advantages/disadvantages of enum over immutable?

Was it helpful?

Solution

  1. An enum is only an rvalue, not an lvalue. It has no address.
  2. An enum can only be a compile time constant, not a runtime constant.
  3. Enums don't add any bloat to the object file.
  4. Enums compile faster and use less memory at compile time. Usually it's negligible, but if you're doing sufficiently complicated metaprogramming it can start to matter.

In general, for things that are compile-time constants as opposed to runtime constants, there's no disadvantage to using an enum, and it has the advantages of making your intentions absolutely clear and being marginally more efficient.

Edit: One other use case for enums can be disambiguating to the compiler whether a function should be evaluated at runtime or compile time. If the result of a function is assigned to an immutable stack variable, the function will be evaluated at runtime. If you use an enum in the same scope, the result will be evaluated at compile time.

OTHER TIPS

IIRC in D enum A = B; is more or less the same things as #define A B is in C. It is always subbed in as a literal in any expression that uses it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top