On Wednesday, October 23, 2024 9:06:46 AM MDT Salih Dincer via Digitalmars-d- learn wrote: > The code also compiles like this. In this case, can we say that > there are 3 solutions or are static and enum actually the same > thing?
static and enum are not the same thing. An enum has no memory location, and you can't take its address. Rather, it's value is effectively copy-pasted wherever it's used (which is why using stuff like arrays for enums generally isn't a great idea, since that results in a bunch of allocations; string literals avoid that problem due to how the compiler handles those, but other array literals normally all result in allocations). enum values (rather than enum types) are called manifest constants and are essentially the D equivalent to when you use C's #define to declare a value. A static variable on the other hand is a variable and has an address. So, whenever you use it, that variable is used, and you avoid allocations - but then you can't make the code that uses it pure unless the variable is immutable, since it could change, which goes against pure's inability to access global, mutable state. The part that's the same between static variables and enums is that if they're directly initialized, that value has to be known at compile time. So, they both can be used in a variety of circumstances where you need to guarantee that something is done at compile time. - Jonathan M Davis