Just a friendly reminder about using arrays in boolean conditions
kdevel
kdevel at vogtner.de
Sun Nov 17 21:50:18 UTC 2024
On Sunday, 17 November 2024 at 16:47:39 UTC, Nick Treleaven wrote:
> [...]
> It was deprecated and then un-deprecated - see
> https://issues.dlang.org/show_bug.cgi?id=4733#c38 for why it
> was problematic, possible solutions and also a link to a 2015
> discussion.
Problematic is valid code like
if (auto arr = make_me_an_array ()) {
...
}
There is another interesting aspect as Steven pointed out in that
2015 discussion [1]:
|| The "truthiness" of an array says it's true ONLY if both the
|| pointer and length are 0.
| Ugh, *false* only if they are both 0. If either are not zero,
| then it's true.
And later he stated [2]
| arr.ptr == null -> arr contains a null pointer (length could
| technically be non-zero).
My question is: Is it possible that a valid D program gets into a
state where an array has ptr == null and length > 0? If so, how?
Such a "null array" can at least not be printed:
import std.stdio;
void main ()
{
int [] arr;
struct V {
size_t length;
void *ptr;
}
auto q = cast (V *) &(arr);
(*q).length = 2;
writeln (arr); // segfault in formatValueImpl
}
[1] Re: string <-> null/bool implicit conversion
https://forum.dlang.org/post/mr54qg$15qj$1@digitalmars.com
[2] https://forum.dlang.org/post/mr72sf$2sc7$1@digitalmars.com
More information about the Digitalmars-d
mailing list