This syntax regarding null checking baffles me

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun Jan 10 10:42:48 UTC 2021


On Saturday, January 9, 2021 2:02:33 PM MST kdevel via Digitalmars-d wrote:
> On Thursday, 7 January 2021 at 22:42:40 UTC, Jonathan M Davis
> wrote:
>
> [...]
>
> > That and using ! is more consistent with what the C family of
> > languages typically does. C-derived languages don't typically
> > try to make sentences like "is not" would do. Having is and !is
> > is also more consistent with == and !=. "is not" wouldn't
> > really fit the rest of the language.
>
> Idiomatic C is of course [1]
>
>     char *p = ...
>     if (p) ...
>
> This form seems to be applicable for pointers in D, too. And also
> for class variables
>
>     class C { ...
>     C c;
>
> I wonder if there is a difference between
>
>     if (c)
>
> and
>
>     if (c ! is null).
>
> [1]
> https://stackoverflow.com/questions/3825668/checking-for-null-pointer-in-c-c
> /3825704#3825704

IIRC, if the class overrides opCast for bool, then

    if(c)

will cast the object to bool and use the result for the if condition,
whereas

    if(c !is null)

always checks whether the reference is null.

- Jonathan M Davis





More information about the Digitalmars-d mailing list