On Thursday, 19 November 2015 at 03:53:48 UTC, 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.

Comparison is ok, weird behavior manifests in boolean context:
void main()
{
        int[] a = [0, 1, 2];
        //4002E000 3
        assert(a != null);
        assert(!!a); //passes, ok
        
        a.length = 0;
        //4002E000 0
        assert(a == null);
        assert(!!a); //still passes!
}

Reply via email to