Casting between different sized integer references

Started by
10 comments, last by EarthBanana 10 years, 9 months ago

Interestingly, GCC 4.8 does not even warn about that code of yours although it's arguably in violation of the standard which says "A reference shall be initialized to refer to a valid object or function" (8.3.2) with "valid" being the important bit.

Since originalInt is not of a type that the new reference type can accomodate, it isn't a valid object (well, originalInt itself is a valid object, but result of the cast which the reference is initialized with isn't). You would think that this is obvious to the compiler, too. But maybe it's because of the cast operation. Probably the compiler assumes "programmer said cast, so he knows what he's doing".

He cast a POD to a POD so it's valid as long memory (size) constraints are honored and they are since it's a smaller.

- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Advertisement

Unspecified behavior not undefined behavior.

You're probably looking at the section of the standard regarding reinterpret_cast which states that the pointer value of the reinterpret_cast is unspecified. However, you're still modifying an object through an lvalue that is different than its dynamic type (and doesn't differ only in cv-qualifiers or signed/unsigned, isn't part of an aggregate, etc.), which is undefined behavior. See section 3.10 in the standard (all versions). (With the exception that uint8_t is probably a typedef for unsigned char, and modifying an object through an lvalue of char or unsigned char isn't undefined behavior. The largerThanOriginal is definitely undefined since there's no way for it to be a typedef for char or unsigned char and still have the example compile.)

this topic is a bit over my head... i guess its back to school

This topic is closed to new replies.

Advertisement