Thread overview
const pointers C vs. D
Feb 04, 2020
Johann Lermer
Feb 04, 2020
Dennis
Feb 06, 2020
Johann Lermer
February 04, 2020
Hi,

I'm just wondering about defining const pointers and if there's a difference in C and D.

in C, this works:

const char* text = "Hello";
text = "world";

but in D it doesn't, because the char* is const. Ff I would like tho have the same behaviour in D as in C, I need to write:

const (char)* text = "Hello";
text = "world";

In C, this would not be valid. So the question for me now is: is const char* in D different from C?

February 04, 2020
On Tuesday, 4 February 2020 at 10:06:03 UTC, Johann Lermer wrote:
> In C, this would not be valid. So the question for me now is: is const char* in D different from C?

Yes, const char* in D reads as const(char*), so it is a char* that cannot be modified.
This is similar to the C code:

char *const text = "Hello";

However, because of transitivity, the characters also can't be modified (unlike C).
For a mutable pointer to const characters, you indeed do const(char)*.

See also:
https://dlang.org/articles/const-faq.html

>C++ has a const system that is closer to D's than any other language, but it still has huge differences:
>
>- const is not transitive
>- no immutables
>- const objects can have mutable members
>- const can be legally cast away and the data modified
>- const T and T are not always distinct types


February 06, 2020
On Tuesday, 4 February 2020 at 10:17:39 UTC, Dennis wrote:
>>C++ has a const system that is closer to D's than any other language, but it still has huge differences:

Thanks, that clears it up a bit!