char[] == null
Chris Wright via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Wed Nov 18 21:18:19 PST 2015
On Thu, 19 Nov 2015 03:53:46 +0000, Meta wrote:
> On Wednesday, 18 November 2015 at 23:53:01 UTC, Chris Wright wrote:
>> ---
>> char[] buffer;
>> if (buffer.length == 0) {}
>> ---
>
> This is not true. Consider the following code:
>
> import std.stdio;
>
> void main()
> {
> int[] a = [0, 1, 2];
> //4002E000 3
> writeln(a.ptr, " ", a.length);
> //Is not triggered, obviously assert(a == null);
>
> a.length = 0;
> //4002E000 0
> writeln(a.ptr, " ", a.length, " ", a);
> //Is not triggered, not as obvious assert(a == null);
> }
>
> There are cases when an array may have 0 length but a non-null pointer.
> If you want to check if an array's length is 0, you must explicitly
> check its length member. Checking if an array is equal to null only
> compares its pointer field to null. It does *not* check the length.
I tested the behavior and it matches what I said earlier:
---
auto c = "hello world".dup;
auto b = c[0..0];
writeln(b == null); // prints true
writeln(b.ptr == null); // prints false
---
This is because array comparison is a memberwise comparison and not a
reference comparison, as you can see more clearly with:
---
enum int[] a = [1, 2, 3];
writeln(a == a.dup); // prints true
---
Or you can check the runtime's implementation of array equality at
https://github.com/D-Programming-Language/druntime/blob/master/src/
object.d#L437 .
Just for fun, is an array ever not equal to itself?
More information about the Digitalmars-d-learn
mailing list