use of if (!cptr) and if (cptr), where cptr is a *
Erik Murrey
erik at mpx2.mpx.com
Wed Jul 19 22:18:05 AEST 1989
In article <93 at microsoft.UUCP>
>In article <10099 at mpx2.mpx.com> erik at mpx2.mpx.com (Erik Murrey) writes:
>>
>>Would (!sptr) break anywhere? Should it be discouraged?
>
>It will break if NULL != 0. This is rare in my experience. In fact
>so rare that most programs would break in such an environment. Besides
>such obvious problems as the above code, there are places where an
>array set to zero is then assumed to be an array of NULL pointers,
>and numerous other implicit uses of the fact that NULL == 0 (usually).
Yes, I know, but what happens when sizeof(int) != sizeof(char *)? My
original question wasn't stated too clearly.
Suppose a char * is 6 bytes, and an int is 4. Suppose the upper 2 bytes
are used as some sort of descriptor. Now suppose malloc() returns
a new memory block which just happens to be at the beginning of a new
page, and our char * looks like:
NN NN 00 00 00 00
(NNNN is our descriptor).
Now, what happens with:
if (cptr == 0) ? Does the compiler cast the cptr to an int, and loose
the descriptor? (And tell is that it is null?)
How about:
if (!cptr) ?
It would seem to me that the second example would probably work on
such architectures, where the first might fail. On the other
hand, I'm not a compiler writer.
I but more nit picking:
>
>>In fact, I much prefer (from a C style article posted a few years back):
>>
>>x()
>>{
>> if (sptr= (struct xyzzy *)malloc(...), !sptr)
>> fatal("cannot malloc");
>>}
>
>This was from a *style* guide?
Yes, and I wish I kept a machine copy to post.
>Yeah I suppose it works, though I am
>too lazy to check if the comma operator has a guaranteed order of
>evaluation. I seldom use it.
>
>Anyway, why the spurious comma operator? Much simpler to write:
>
> if (! (sptr = (struct xyzzy *)malloc(...))
> fatal(...);
>
And most people seem to like this one best, although I dislike it
because of the extra level of parentheses. Consider:
struct xyzzy {
int x;
} *my_function();
{
struct xyzzy *sptr;
if ((sptr= my_function())->x == 0)
printf("x is zero\n");
}
vs.
{
struct xyzzy *sptr;
if (sptr= my_function(), sptr->x == 0)
printf("x is zero\n");
}
I think the second is much clearer. This looks even better as the
pointers get more complex, since the pointer operators go right
on the ptr itself, and not on an expression.
... Erik
--
Erik Murrey /| // /~~~~/ | /
MPX Data Systems, Inc. / | / / /____/ |/
erik at mpx.com / / / / /| Data Systems, Inc.
{vu-vlsi, bpa, cbmvax}!mpx1!erik / / / / |====================
More information about the Comp.lang.c
mailing list