S
sunglo
Some time a go, in a discussion here in comp.lang.c, I learnt that it's
better not to use a (sometype **) where a (void **) is expected (using
a cast). Part of the discussion boiled down to the rule: if I cast a
(sometype **) to a (void **) I am making a number of assumptions about
the implementation's (void **) representation and length. Specifically,
if I do the above cast I'm assuming that a (sometype **) and a (void
**) have the same size and representation, and this might not always be
true. Ok, all clear up to this point.
But now my question is: does the above rule generalize to *every*
possible cast (expecially those where pointers are involved)? Is every
explicit cast unsafe? (Here I'm not talking about conversions to/from
void *, which I know are safe if performed implicitly by the language.
I also know that casts are better avoided unless strictly needed. But
I'm curious to know how things work).
As an example, look at the widely used cast (struct sockaddr_in *) to
(struct sockaddr *). Is that safe?
Seems to me that, as in the case of (void **), that cast assumes that
the size and representation of a (struct sockaddr *) are the same of a
(struct sockaddr_in *). Should this be done using an intermediate (void
*)?
What is (if any) the general rule? Or, in general, what can be said and
assumed about the casted object?
Thanks and sorry for the possibly silly questions.
better not to use a (sometype **) where a (void **) is expected (using
a cast). Part of the discussion boiled down to the rule: if I cast a
(sometype **) to a (void **) I am making a number of assumptions about
the implementation's (void **) representation and length. Specifically,
if I do the above cast I'm assuming that a (sometype **) and a (void
**) have the same size and representation, and this might not always be
true. Ok, all clear up to this point.
But now my question is: does the above rule generalize to *every*
possible cast (expecially those where pointers are involved)? Is every
explicit cast unsafe? (Here I'm not talking about conversions to/from
void *, which I know are safe if performed implicitly by the language.
I also know that casts are better avoided unless strictly needed. But
I'm curious to know how things work).
As an example, look at the widely used cast (struct sockaddr_in *) to
(struct sockaddr *). Is that safe?
Seems to me that, as in the case of (void **), that cast assumes that
the size and representation of a (struct sockaddr *) are the same of a
(struct sockaddr_in *). Should this be done using an intermediate (void
*)?
What is (if any) the general rule? Or, in general, what can be said and
assumed about the casted object?
Thanks and sorry for the possibly silly questions.