Is there any real reason to use "const"?
rempas
rempas at tutanota.com
Mon Jan 24 11:23:38 UTC 2022
On Monday, 24 January 2022 at 10:49:36 UTC, Dom DiSc wrote:
> You need const for functions that need to be able to take a
> mutable or immutable variable as parameter. And as you don't
> know which it is, you have to either propagate the constness or
> make a mutable copy if you want to call a function (depending
> if the called function has its parameter declared const or
> not). So better to declare const wherever that is possible, to
> _avoid_ making useless copies.
> I would NEVER EVER declare a variable const. It's always either
> mutable or immutable. I would go as far as forbidding to
> declare variables const, it's just confusing and useless. const
> is only for parameters.
That's what I'm saying. If there were no "const" and it was up to
the programmer to decide what to do, we wouldn't had to worry
about all that. Is you string pointing to a string literal? Then
don't use the "add" function to add more data to it! Or maybe
have a member in the "string type" that will check if the string
points to a string literal and in this case, allocate memory (for
both the old and the new value), copy the old value and then add
the new value! This is just so simple and easy for both the
creators of the language and the users
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? Any..
"practical" reason so to say.
More information about the Digitalmars-d
mailing list