digitalmars.D.learn - const vs immutable - when declaring a variable
- Brother Bill (9/9) Oct 17 Is there any difference when declaring a variable of using const
- Steven Schveighoffer (20/29) Oct 17 Yes, a `const` declaration types the value as `const`, whereas an
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!"; ```
Oct 17
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
Oct 17








Steven Schveighoffer <schveiguy gmail.com>