Is there any real reason to use "const"?

Mark smarksc at gmail.com
Mon Jan 24 12:28:25 UTC 2022


On Monday, 24 January 2022 at 10:06:49 UTC, 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?
>
> 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. To 
> me, "const" has a lot of burdens like:
>
> "should we use it all the time if we don't want to be sure that 
> we won't modify a variable or only for critical ones?"
>
> "Then in this case, why not make "const" the default and use 
> another word to allow a variable to be mutable (just like Rust 
> and other languages)?"
>
> Also another problem is that I don't like the way "const" is 
> treated in functions. For example, you cannot past "const" 
> variables to functions that take non-const parameters even if 
> we are using variables which are ALWAYS copied (which means 
> than modifying them will not modify the original value). This 
> is stupid because if I want to support "const" for a function, 
> I need to make an extra instruction to copy the value to a new 
> non-const variable that is created inside the function and make 
> an extra instruction. Copying a value is not a slow operation 
> but it can be for a big struct. And in any case, it is stupid 
> and it pisses me off...
>
> So yeah, I would like to know as soon as possible if there are 
> any real reasons to support something like that so I can 
> implement it.
>
> What do you guys think?

AFAIK, const is a contentious topic. You can find many previous 
discussions on this forum and elsewhere revolving around the 
questions of how to use const, whether D's const is generally 
useful, the effect it has on APIs, whether we need 
tail-const/head-mutable in the language, etc.  Jonathan M Davis 
wrote an article which covers some of these questions (and also 
considers C++'s const):
http://jmdavisprog.com/articles/why-const-sucks.html
The article is 4 years old but I don't think much has changed 
since then.

I know that Rust also has const (by default; non-const variable 
are marked with `mut`) but I don't have enough experience to give 
an honest opinion on it.


More information about the Digitalmars-d mailing list