www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - const pointers C vs. D

reply Johann Lermer <jlermer elvin.eu> writes:
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?
Feb 04 2020
parent reply Dennis <dkorpel gmail.com> writes:
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
Feb 04 2020
parent Johann Lermer <jlermer elvin.eu> writes:
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!
Feb 06 2020