www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - const vs immutable - when declaring a variable

reply Brother Bill <brotherbill mail.com> writes:
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
parent Steven Schveighoffer <schveiguy gmail.com> writes:
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