Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

You can still cast INT_MAX to short no matter how you spell the cast, and the result won't be correct.


There 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.


> 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.


> 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.


You shouldn't be using INT_MAX for the last decade or so. That's why std::numeric_limits exist.


You want me to type `std::numeric_limits<int>::max()` in a forum comment? Bit long.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: