Declaring a single const: enum vs const vs immutable
IchorDev
zxinsworld at gmail.com
Thu Sep 11 08:34:27 UTC 2025
On Wednesday, 10 September 2025 at 17:33:48 UTC, H. S. Teoh wrote:
> `enum` defines a compile-time constant. It occupies no space,
> and its value is "copied" into every expression in which it
> appears.
> [...]
> `const` and `immutable` are type qualifiers, and declaring a
> constant with them creates a variable in memory containing that
> value.
Well said. It's an important and easy-to-misunderstand part of
the language, and you explained it very well here.
> const in D is [...] infectious (you cannot modify data through
> a const reference even if the data itself is mutable).
I'd like to clarify this a little:
D's type qualifiers (`const`, `immutable`, `shared`, and `inout`)
are usually described as being 'transitive'. What that means is
that anything inside a `const` object is also `const`, and
anything inside a `shared` object is also `shared`, etc.
So if a struct instance is `const`, then its fields are `const`;
if an array is `const`, then its elements are `const`; and so on.
> D defines `string` as `immutable(char)[]`, i.e., a mutable
> reference to an immutable array of characters.
Bonus fact: `string` is not a keyword in D! (a fact that I feel
compelled to point out because I've seen SO many people assume
that it's a keyword!)
> Finally, recommendations:
> [...]
Very good advice also.
More information about the Digitalmars-d-learn
mailing list