NULL pointer
Ron Natalie <ron>
ron at brl-sem.ARPA
Tue Nov 19 19:35:34 AEST 1985
> How many times do people have to go over this? Perhaps the problem is that
> people don't understand what a cast does!
>
> A cast does NOT change the bit pattern! As a matter of fact, it is a means
> of preventing a conversion that DOES change the bit pattern! A cast simply
> changes the PRESUMED type of a stored bit-pattern, without changing the
> pattern itself. (The only exception is extension or truncation to match
> the size of the destination type. When extending you can use any fill bits you
> consider reasonable; the uSOFT C compiler inserts the data segment number when
> converting near pointers types to far pointer types). If the resulting type
> still does not match the target, then a conversion occurs DURING THE ASSIGNMENT!
I don't know how many times you have been over it, but casts do change the
bit pattern of what they apply to, if necessary.
Let's take out our copies of Kernighan and Ritchie, turn to page 42 and
read aloud:
"The precise meaning of cast is in fact as if expression were
assigned to a variable of the specified type, which is then
used in place of the whole construction"
Consider the following:
float f1, f2;
union {
float union_float;
int union_int;
} samebits;
main() {
f1 = (float) -1;
samebits.union_int = -1;
f2 = samebits.union_float;
printf("f1 = %f, union_float = %f, f2 = %f\n",
f1, samebits.union_float);
}
If casts worked you way, I would assign all ones to the data area taken
up by f1. No conversion from int would occur because I have now changed
the type to float and the assignment sees that the left side and the
right side now have the same type. Just to check the computation the
other way, I set up a union that guarantees that the float and the int
will be colocated and no automatic type conversion of any kind will occur.
What happens when we run this on an ANSI conforming C compiler
f1 = -1.000000, union_float = 0.000000, f2 = 0.000000
Surprise, type casts change the data. Under your scheme, how do you
deal with a cast to something with a different size than the original object?
>
> The ONLY totally correct thing to do if machines with non-zero nulls
> are involved is to assign 0 to a pointer variable, and then pass the variable.
> So if you want to be totally correct you would define NULL like this:-
>
> #define NULL (___p=0)
> static char *___p;
This would be exactly the same as casting 0 to (char *) without the
side effect of loading ___p, BY DEFINITION.
CASTS do not change the value of the thing to the right of the expression,
but they will change the MACHINE REPRESENTATION to that of the new type.
If you worked on machines like I've done that have 5 different types of
pointer (character, word, half-word, quarter-word, and function)
representation, you'd appreciate the way cast works.
-Ron
More information about the Comp.lang.c
mailing list