On Sunday, 15 August 2021 at 08:11:39 UTC, rempas wrote:


I mean that in C, we can assign a string literal into a `char*` and also a `const char*` type without getting a compilation error while in D, we can only assign it to a `const char*` type. I suppose that's because of C doing explicit conversion. I didn't talked about mutating a string literal

The D `string` is an alias for `immutable(char)[]`, immutable contents of a mutable array reference (`immutable(char[])` would mean the array reference is also immutable). You don't want to assign that to a `char*`, because then you'd be able to mutate the contents of the string, thereby violating the contract of immutable. (`immutable` means the data to which it's applied, in this case the contents of an array, will not be mutated through any reference anywhere in the program.)

Assigning it to `const(char)*` is fine, because `const` means the data can't be mutated through that particular reference (pointer in this case). And because strings in C are quite frequently represented as `const(char)*`, especially in function parameter lists, D string literals are explicitly convertible to `const(char)*` and also NUL-terminated. So you can do something like `puts("Something")` without worry.

This blog post may be helpful:

https://dlang.org/blog/2021/05/24/interfacing-d-with-c-strings-part-one/

Reply via email to