Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Phobos use enum for constants?

Tags:

enums

d

phobos

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?

like image 926
Peter Alexander Avatar asked Sep 01 '10 22:09

Peter Alexander


2 Answers

  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.

like image 169
dsimcha Avatar answered Oct 20 '22 10:10

dsimcha


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.

like image 30
BCS Avatar answered Oct 20 '22 12:10

BCS