TITLE: more on static_cast and reinterpret_cast (Newsgroups: comp.std.c++, 18 Feb 97) [ This is a continuation on a thread discussing static_cast and reinterpret_cast. The original code in question looked something like: T2* pt2; T1* pt1 = static_cast(static_cast(pt2)); versus T1* pt1 = reinterpret_cast(pt2); CLAMAGE: Stephen.Clamage@Eng.Sun.COM (Steve Clamage) >>As a practical matter, when T1 is pointer-to-struct and T2 is char*, the >>double cast is likely to behave as you expect, and is likely to have the >>same result as reinterpret_cast. If that happens not to be true on >>some platform, you are out of luck. The standard does not promise that >>it is so, as far as I can tell. MASHLAN: rmashlan@r2m.com (Robert Mashlan) >I'm still not understanding why this would be so -- is there something >magical about the void* returned from malloc, as compared to a void* >(assumed to have the appropriate alignment) that points to a middle of >a malloc'ed block? CLAMAGE: The cast from the void* returned from malloc works (within specified limits) because a language rule says it must. If you call malloc to get N bytes, the returned address must be suitably aligned for any data type of N bytes. If you adjust the pointer to point inside that memory space, whether it is suitably aligned for your particular purpose depends on the details of the platform, the implementation, and the particular value of the pointer. Many popular platforms feature byte-addressed memory, and pointers which are simple addresses, all pointers being the same size and having the same representation. For such a platform, it would be reasonable to expect the result of any reinterpret_cast, or any static_cast to or from void*, to leave the bits unchanged. It would also be reasonable to expect that if you obey alignment constraints, any pointer conversion will have a simple and predictable result. Properties like "all pointers look alike", "all pointers are the same size", "reinterpret_cast doesn't change the bits" are not universal, however, and the standard doesn't require them to hold. One of the major reasons for adding the four new cast types to C++ was to make it easy to find casts in a program, so that each cast could be inspected when porting code to determine whether it makes unportable assumptions. All safe and portable type conversions can occur implicitly. Any conversion requiring a cast is potentially unportable or is otherwise potentially dangerous.