Is there any real reason to use "const"?

Steven Schveighoffer schveiguy at
Mon Jan 24 14:40:33 UTC 2022

On 1/24/22 5:06 AM, rempas wrote:
> Rather than just tell the compiler to not allow me to modify a variable 
> (like I don't know what I'm doing with my program), are there any reason 
> to use "const" variables?

If you want the compiler to help you prevent mistakes, yes. If you 
don't, then no.

Other than that, if you want to write a library and have it most 
accessible to others that may prefer to use const, you should use const, 
as it will allow the most usage.

> Other than out of curiosity, I'm actually asking because I'm writing a 
> transpiler and I want to know if I should support "const" (or the 
> concept of immutability in general) or not.

immutable/const is purely a compile-time concept. It's not reflected in 
the final binary, so it's not necessary to forward the attributes to a 
language that doesn't support it.

Same thing with types (see for instance, TypeScript compiled to JavaScript).


More information about the Digitalmars-d mailing list