On 9/25/14 8:24 PM, AsmMan wrote:
On Thursday, 25 September 2014 at 12:43:57 UTC, Steven
Schveighoffer wrote:
On 9/25/14 2:41 AM, SlomoTheBrave wrote:
On Thursday, 25 September 2014 at 05:29:37 UTC, AsmMan wrote:
Does D has C#'s string.Empty?
string.init ?
----
string a;
a = string.init;
assert( a == "");
----
does the job for the type string at least.
null also works. In fact, in the above, a is already string.init or
null before assigning (D always initializes variables unless asked not
to).
a = null; // same as a = string.init;
It made me a bit confusing. How is the implementation of string
comparasion in D? (if someone could point to actual code used in
these comparasion would be really great otherwise I'll check out
assembly output, maybe) in no language I know of (including C#)
"" == null is true
A string is simply an array of char in D, similar to how it is in C. It
is NOT a full-blown class type, unlike many languages, C# included.
The code to compare all arrays is somewhere in the runtime, not sure
exactly where, but the compiler has some tricks it can use when
generating code, so it may not call those functions.
Essentially, comparison is a foreach over the length of the arrays. If
they are null, then their lengths are 0. But the actual pointers may be
different, it doesn't matter.
Interestingly:
string s = "";
string t = [];
Note that both are valid, because both are arrays. but...
assert(s.ptr !is null);
assert(t.ptr is null);
Why? Because string literals are special in that they actually point to
null terminated memory. So "hello" is actually an array of 5 chars + a
6th '\0' char. However, the length of "hello" is set to 5. The reason
for this is so you can just pass a string literal into a C function, and
it works. But due to this rule, "" cannot point at null, it must point
to valid memory for the terminating '\0'.
An array does not need to conform to C rules, so it can safely set the
pointer to null.
If we compare s and t:
assert(s == t);
assert(s !is t);
this is because == checks to see if the arrays are *equivalent*, meaning
they have the same length, and all the elements are equivalent. 'is'
checks to see if the arrays are *identical*, meaning they point at the
same memory.
-Steve