Casting NULL again

guy at gorodish.UUCP guy at gorodish.UUCP
Wed Jan 28 14:34:16 AEST 1987


>Thanks for your comments on this matter. Unfortunately, most
>of you misunderstood what I wanted. I realize that under some
>machines ints are 16 bits and pointers are 32. I have a MAC and
>thats the case there and I often have to pass parameters as
>(long)NULL to get the right number of bytes passed.
>That's nothing to do with pointers per se,=that's a "problem" of
>dealing with long int parameters.

The person who claimed that the reason you cast NULL to a particular
pointer type is that pointers to different types might have different
sizes is only partially correct.  The *real* reason is that pointers
to different types have different types!  Too many C programmers feel
that correct C is anything they can get away with, and too many
programmers get burned by this.

Yes, you can probably get away with not casting NULL, or casting to
"long", or casting it to "char *" in all cases, or something else
wrong like that.  However, you'll get surprised if you have a machine
where null pointers aren't represented with the same bit pattern as
an integral zero, or where pointers contain tags that indicate the
data type that they refer to.  (Casting them to "long" is just
totally wrong - this won't even work on "normal" machines if "long"
and the pointer type in question aren't the same size!)

Furthermore, programs like "lint" will complain if you don't cast
them.  Running "lint" is a good way of catching many bugs, some of
which manifest themselves to an inter-module procedure call checker
like "lint" as a mismatch in argument types.  C has a type system,
and if you use it it can help you write correct code.

No, I don't know of any machines offhand that are byte-addressible
(but why is this relevant?  Do you think you'll never work on any
machine that isn't?  I certainly wouldn't make that prediction about
myself...) and where pointers to different types of objects have
different representations (the size isn't the only characteristic of
the representation that's important).  However, that's not an excuse
to drop the casts.  The fact that something happens to work on the
machines you know about doesn't say anything about whether they'll
work on the machine you next have to deal with.



More information about the Comp.lang.c mailing list