Is there any real reason to use "const"?

Dennis dkorpel at gmail.com
Mon Jan 24 12:31:43 UTC 2022


On Monday, 24 January 2022 at 11:23:38 UTC, rempas wrote:
> My point is if there is a true reason to implement "const" 
> itself other than just protecting programmers that haven't read 
> the documentation and are trying to modify a string literal?

There's this idea among some programmers that to prevent software 
bugs, we just need more well-trained / competent people, "like 
myself". This opinion tends to wane over time as you start 
writing those bugs you thought you'd never write.

I never understood the idea of people always including {} braces 
in if-statements and for-loops. The idea is to prevent this:

```D
if (x)
     y();
     z();
```
What idiot would write something like that, `z()` is obviously 
not part of the if-statement anymore right? One day I had a 
single-line for-loop body, and to fix an error I quickly added an 
`import` statement above it, pushing the for-loop body outside 
the for-loop scope. Oops.

Yesterday I wrote a bug like this:
```D
void alphabeta(ref Field field, /*...*/) {
     // (...)
     Field fieldCopy = field;
     field.modify(); // < should be fieldCopy.modify()
     alphabeta(fieldCopy);
     // (...)
}
```
I was debugging it and noticed that I might as well mark the 
`field` parameter `const` since it wasn't supposed to change. The 
next compile I immediately got an error pointing at the bug!

Usually I mark variables/functions as strict as possible as early 
as possible, `const` / `scope` / `pure` / `@safe` etc. I don't 
know how many bugs I would have written when I wouldn't do that, 
but it's also comforting knowing that I don't have to worry about 
accidentally breaking these properties I rely on when I modify a 
part of the code days or weeks later. Because that's how it gets 
you: sure, you can do these checks yourself the first time you 
write a function, but will you do them again every time you make 
a modification in the future? The compiler can, you likely won't.

That said, it can also be annoying marking all function 
parameters `const` appropriately to convince the compiler that 
you indeed don't modify a `const` variable. I've heard of C++ 
people applying a macro `#define const` to a remove all `const` 
from a const-correct codebase because they don't like dealing 
with it. If you don't think it's worth it, you can not mark 
parameters `const` if you also don't mark your variables `const`.


More information about the Digitalmars-d mailing list