== comparison of string literals, and their usage

diniz diniz at posteo.net
Sun Apr 7 17:03:08 UTC 2019


Le 07/04/2019 à 14:23, bauss via Digitalmars-d-learn a écrit :
> On Saturday, 6 April 2019 at 19:47:14 UTC, lithium iodate wrote:
>> On Saturday, 6 April 2019 at 15:35:22 UTC, diniz wrote:
>>> So, I still could store and use and compare string pointers myself [1], and 
>>> get valid results, meaning: pointer equality implies (literal) string 
>>> equality. Or am I wrong? The point is, the parser, operating on an array of 
>>> prescanned lexemes, will constantly check whether a valid lexeme is present 
>>> simply by checking the lexeme "class". I don't want that to be a real string 
>>> comp, too expesensive and for no gain.
>>>
>>> [1] As in the second comp of your example:
>>> void main()
>>> {
>>>     auto c2 =  "one" == "two";
>>>     auto c1 =  "one".ptr is "two".ptr;
>>> }
>>
>> Not quite. D-strings strictly consist of pointer *and* length, so you need to 
>> compare the .length properties as well to correctly conclude that the strings 
>> equal. You can concisely do that in one go by simply `is` comparing the array 
>> references as in
>>
>> string a = "hello";
>> string b = a;
>> assert(a is b);
>> assert(a[] is b[]);
>>
>> Of course, if the strings are never sliced, you can just compare the pointers 
>> and be done, just make sure to document how it operates. Depending on the 
>> circumstances I'd throw in some asserts that do actual strings comparison to 
>> verify the program logic.
> 
> To add onto this.
> 
> Here is an example why it's important to compare the length as well:
> 
>      string a = "hello";
>      string b = a[0 .. 3];
> 
>      assert(a.ptr == b.ptr);
>      assert(a.length != b.length);


Thank you! Very clear :-).

-- 
diniz {la vita e estranj}


More information about the Digitalmars-d-learn mailing list