Re: pointers for c vs c++
On Feb 4, 9:54 am, Bart van Ingen Schenau
<Bart.van.Ingen.Sche...@ict.nl> wrote:
On Feb 3, 7:43 pm, Juha Nieminen <nos...@thanks.invalid> wrote:
James Kanze wrote:
And within the bounds of what each language supports. C
doesn't have an implicite pointer to derived to pointer to
base conversion, for example (for the obvious reason that
it doesn't have derived and base).
Is it so that casting a pointer to a different type in C
never changes the internal value of the pointer,
No, that is not true. C does not guarantee that all pointers
have the same size and/or representation, so casting between
pointer types may change the representation of the pointer.
while the same is not true for C++ (where certain casts in
an inheritance hierarchy can change the actual value of the
pointer)?
It is true that C++ has more situations (and more regularly
occurring) where a pointer conversion results in a change of
representation.
But there's a very big difference in the semantics which can be
associated with such changes. In C, if the target pointer has
sufficient size, and the source pointer is sufficiently aligned,
it is guaranteed that the results of the cast will point to the
same memory address---have the same "internal value" (even if
the representation of that value has changed); the "internal
value" will only be different if it can't be represented in the
target type. In C++, a static_cast does not have this
guarantee. (reinterpret_cast and const_cast do.)
Note that even if there is no difference in size and
representation, the standard doesn't guarantee that the bit
pattern will be the same. A compiler for an Intel with
physically segmented addressing (the original 8086), for
example, the compiler could legally "normalize" the pointer (so
that the offset was in the range [0...16)) when it was
converted. (Of course, it doesn't make any sense to do so, and
I've never heard of a compiler that did, but such an
implementation would be legal.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34