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

rempas rempas at tutanota.com
Sun Aug 15 06:10:53 UTC 2021


So when I'm doing something like the following: `string name = 
"John";`
Then what's the actual type of the literal `"John"`?
In the chapter [Calling C 
functions](https://dlang.org/spec/interfaceToC.html#calling_c_functions) in the "Interfacing with C" page, the following is said:
> Strings are not 0 terminated in D. See "Data Type 
> Compatibility" for more information about this. However, string 
> literals in D are 0 terminated.

Which is really interesting and makes me suppose that `"John"` is 
a string literal right?
However, when I'm writing something like the following: `char 
*name = "John";`,
then D will complain with the following message:
> Error: cannot implicitly convert expression `"John"` of type 
> `string` to `char*`

Which is interesting because this works in C. If I use `const 
char*` instead, it will work. I suppose that this has to do with 
the fact that `string` is an alias for `immutable(char[])` but 
still this has to mean that the actual type of a LITERAL string 
is of type `string` (aka `immutable(char[])`).

Another thing I can do is cast the literal to a `char*` but I'm 
wondering what's going on under the hood in this case. Is casting 
executed at compile time or at runtime? 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?

I hope all that makes sense and the someone can answer, lol


More information about the Digitalmars-d-learn mailing list