Why does Phobos use enum for constants?
Asked Answered
V

2

16

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?

Vaclav answered 1/9, 2010 at 22:54 Comment(0)
R
22
  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.

Ridgeling answered 2/9, 2010 at 0:18 Comment(0)
C
4

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.

Cambist answered 2/9, 2010 at 0:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.