== comparison of string literals, and their usage
lithium iodate
whatdoiknow at doesntexist.net
Sat Apr 6 19:47:14 UTC 2019
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.
More information about the Digitalmars-d-learn
mailing list