On 02/19/2012 03:23 AM, Jonathan M Davis wrote:
On Sunday, February 19, 2012 03:01:55 Timon Gehr wrote:
Why does the following code behave funny?
void main(){
string x = " "[1..1];
writeln(cast(bool)x); // true
char[] y = [' '][1..1];
writeln(cast(bool)y); // false
}
Is there any reason for empty arrays to evaluate to true? This is very
bug prone.
Because they're not null. _null_ is what evaluates to false, not an empty
array.
That is my point. It should not be that way. That is utter nonsense. It
is a major wart. (Every literal with a null .ptr evaluates to false,
btw, not just 'null')
But the fact that == treats null and [] as the same thing _does_
understandably cloud things a bit.
Nothing cloudy about that, that is sane behaviour and I want it to be
consistently carried out everywhere. ('is' can still do a binary
compare, that is what it is designed to do.)
But
if(arr)
is lowered to
if(cast(bool)arr)
which checks for null, not empty. So, this is fully expected.
No, it is not what is expected, it is what is _observed_. It is almost
certainly just a bug in the implementation and everyone thought it is
part of the language.
Consider this, and then don't tell me it is not a leftover from the
ancient times when dynamic arrays implicitly converted to their .ptr fields:
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
}
If you want to check whether an array is empty, then check whether it's empty,
not whether
it's true.
I can't help myself noticing that you always seem to defend the position
that makes the code more verbose.