Is there any real reason to use "const"?
rempas
rempas at tutanota.com
Mon Jan 24 11:41:10 UTC 2022
On Monday, 24 January 2022 at 11:15:47 UTC, Dennis wrote:
> On Monday, 24 January 2022 at 10:06:49 UTC, rempas wrote:
>> 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).
>
> You can? This compiles:
> ```D
> struct S {
> int x;
> const(int)[] arr;
> immutable(char)[] str;
> }
>
> void main() {
> const S sc;
> immutable S si;
> f(sc); // mutable copy passed to f
> f(si); // mutable copy passed to f
> }
>
> void f(S s) {
> s.x = 3;
> }
> ```
> It will only error if the type has mutable indirections,
> because then you could violate `const` by changing the contents
> behind the array/pointer.
I thought I tried it out some months ago and it wasn't possible.
Well, turns out that I was wrong about the second part of my
post. And that I'm an idiot of course but this is not something I
didn't knew before neither something that will stop me....
More information about the Digitalmars-d
mailing list