const vs immutable - when declaring a variable
Steven Schveighoffer
schveiguy at gmail.com
Sat Oct 18 01:52:13 UTC 2025
On Friday, 17 October 2025 at 19:49:07 UTC, Brother Bill wrote:
> Is there any difference when declaring a variable of using
> const vs immutable.
>
> Example:
> ```
> const int a = 3;
> immutable int b = 4;
>
> const string c = "Greetings!";
> immutable string d = "D Programmers!";
> ```
Yes, a `const` declaration types the value as `const`, whereas an
`immutable` declaration types the value as `immutable`.
While this is somewhat of an obvious explanation, the differences
are subtle.
* A `const` reference type can point at either a mutable or
`immutable` value. So regardless of where the value is stored,
this has implications on where you can pass the value. You cannot
pass a `const` reference to an `immutable` parameter.
* A non-reference type can be stored as either `const` or
`immutable`, and it's effectively the same thing (value types
such as `int` can be freely implicitly converted between
mutability).
* Taking the *address of* a `const` or `immutable` value keeps
the mutability when passing around, and this has implications as
to what functions can accept such parameters.
My recommendation is to use `immutable` for declaring constants.
Use `const` when you will assign to data that might be either
`immutable` or mutable.
-Steve
More information about the Digitalmars-d-learn
mailing list