D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 7539 - cast(bool) of empty array must result in false
Summary: cast(bool) of empty array must result in false
Status: RESOLVED DUPLICATE of issue 4733
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 normal
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2012-02-18 19:44 UTC by timon.gehr
Modified: 2017-07-03 20:00 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description timon.gehr 2012-02-18 19:44:16 UTC
cast(bool)array must be rewritten to cast(bool)array.length.

assert(!""); // currently fails
assert(![]); // currently passes
assert(![' '][1..1]);  // passes
assert(!" "[1..1]);    // fails

assert(a==b && (!a&&b||!b&&a)); // might fail more or less randomly for dynamic arrays a,b

The current behavior is that cast(bool)array is translated to cast(bool)array.ptr. This is likely a leftover from the times when dynamic arrays implicitly converted to their .ptr properties. It does not convey any useful semantics, yet it is invoked implicitly every time a dynamic array appears in a boolean evaluation context.

struct DynArray{
    size_t length;
    int* ptr;
    alias ptr this;
}
void main(){
    DynArray a;
    int[] b;
    writeln(cast(bool)a); // false
    writeln(cast(bool)b); // false

    a.ptr = new	int;
    writeln(cast(bool)a); // true

    *(cast(int**)&b+1) = new int; // "b.ptr = new int"
    writeln(cast(bool)b); // true
}
Comment 1 timon.gehr 2012-02-18 20:18:38 UTC
More evidence: Currently these both fail to interpret with the same error message.

static assert(cast(int*)[]||1);
static assert(cast(bool)[]||1);

The current semantics were an accident.
Comment 2 bearophile_hugs 2012-02-19 04:57:07 UTC
See also issue 4733
Comment 3 Vladimir Panteleev 2017-07-03 19:17:27 UTC

*** This issue has been marked as a duplicate of issue 4733 ***
Comment 4 timon.gehr 2017-07-03 20:00:38 UTC
:(