Lot's of great information and pointers already. I will try from another angle. :)

On 8/14/21 11:10 PM, rempas wrote:

> So when I'm doing something like the following: `string name = "John";`
> Then what's the actual type of the literal `"John"`?

As you say and as the code shows, there are two constructs in that line. The right-hand side is a string literal. The left-hand side is a 'string'.

>> Strings are not 0 terminated in D. See "Data Type Compatibility" for
>> more information about this. However, string literals in D are 0
>> terminated.

The string literal is embedded into the compiled program as 5 bytes in this case: 'J', 'o', 'h', 'n', '\0'. That's the right-hand side of your code above.

'string' is an array in D and arrays are stored as the following pair:

  size_t length;    // The number of elements
  T * ptr;          // The pointer to the first element

(This is called a "fat pointer".)

So, if we assume that the literal 'John' was placed at memory location 0x1000, then the left-hand side of your code will satisfy the following conditions:

  assert(name.length == 4);    // <-- NOT 5
  assert(name.ptr == 0x1000);

The important part to note is how even though the string literal was stored as 5 bytes but the string's length is 4.

As others said, when we add a character to a string, there is no '\0' involved. Only the newly added char will the added.

Functions in D do not need the '\0' sentinel to know where the string ends. The end is already known from the 'length' property.

Ali

Reply via email to