2 ms·
You can still cast INT_MAX to short no matter how you spell the cast, and the result won't be correct.
by astrange 4y ago
You can still cast INT_MAX to short no matter how you spell the cast, and the result won't be correct.
- germandiago 4y agoThere are more casts than those. Anda reinterpet cast is a superset of a static cast. If you want to narrow, you would use static cast, not reinterpret cast. If you want to reinterpret a set of bytes as another object then you reinterpret cast (actuall use std::bit_cast, will catch more errors,). So yes, you can still do that but consciously. In C you could even turn a cast that is essentially a static cast into a reinterpret cast by accident and the compiler would say nothing.
- astrange 4y ago> If you want to narrow, you would use static cast, not reinterpret cast. But if you do that, it's not safe! It's the same as C, which is not safe - it's "implementation defined". Swift would trap on overflow here.
- germandiago 4y ago> But if you do that, it's not safe! static_cast does narrowing foor the case mentioned. reinterpret_cast would just reinterpret the same bit pattern as another type. Whether it is equivalent or not is another story. For example, casting a float to an int will narrow but also will convert the internal format. You can catch some overflow by {} initialization.
- shaklee3 4y agoYou shouldn't be using INT_MAX for the last decade or so. That's why std::numeric_limits exist.
- astrange 4y agoYou want me to type `std::numeric_limits<int>::max()` in a forum comment? Bit long.