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
?
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
?
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.
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.