char[] == null
Chris Wright via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Nov 18 15:53:01 PST 2015
On Wed, 18 Nov 2015 20:57:06 +0000, Spacen Jasset wrote:
> Should this be allowed? What is it's purpose? It could compare two
> arrays, but surely not that each element of type char is null?
>
> char[] buffer;
> if (buffer == null) {}
'null' is a value of ambiguous type. The compiler finds a set of
compatible types for them by applying known implicit conversions. 'null'
can implicitly convert to 'char[]'.
Arrays, of course, are tuples consisting of a start pointer and length. A
null array is essentially {ptr = null, length = 0}. Array equality is
implemented as, roughly:
---
if (a.length != b.length) return false;
foreach (i, v; a) {
if (v != b[i]) return false;
}
return true;
---
(That's not quite how it's implemented; it uses runtime functions and
indirection. But it's the same algorithm.)
This shows us that all 0-length arrays are equal. Pretty much as we'd
expect. So your code is equivalent to:
---
char[] buffer;
if (buffer.length == 0) {}
---
More information about the Digitalmars-d-learn
mailing list