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

jfondren julian.fondren at gmail.com
Sun Aug 15 07:47:27 UTC 2021


On Sunday, 15 August 2021 at 07:43:59 UTC, jfondren wrote:
> On Sunday, 15 August 2021 at 06:10:53 UTC, rempas wrote:
> ```d
> unittest {
>     char* s = "John".dup.ptr;
>     s[0] = 'X'; // no segfaults
>     assert(s[0..4] == "Xohn"); // ok
> }
> ```
>
>> So am I going to have an extra runtime cost having to first 
>> construct a `string` and then ALSO cast it to a string literal?

In the above case, "John" is a string that's compiled into the 
resulting executable and loaded into read-only memory, and this 
code is reached that string is duplicated, at runtime, to create 
a copy in writable memory.


More information about the Digitalmars-d-learn mailing list