What exactly are the String literrals in D and how they work?

rempas rempas at tutanota.com
Sun Aug 15 09:06:48 UTC 2021


On Sunday, 15 August 2021 at 09:01:17 UTC, jfondren wrote:
> They don't do the same thing. toStringz always copies, always 
> GC-allocates, and always NUL-terminates. `cast(char*)` only 
> does what you want in the case that you're applying it a string 
> literal. But in that case you shouldn't cast, you should just
>
> ```d
> const char* s = "John";
> ```
>
> If you need cast cast the const away to work with a C API, 
> doing that separately, at the point of the call to the C 
> function, makes it clearer what you're doing and what the risks 
> are there (does the C function modify the string? If so this 
> will segfault).

Yeah I won't cast when having a `const char*`. I already 
mentioned that it works without cast with `const` variables ;)




More information about the Digitalmars-d-learn mailing list