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

You're bringing just one specific case where probably is acceptable[1] and ignoring all other cases where it's definitively bad (to narrower type, or mixing floats with ints).

[1] and only when you don't care about overhead of converting from one type.



I couldn't think of anything immediately Evil for that case and wanted to check I wasn't missing something :) The others definitely have badness if you aren't expecting it.

I'm quite surprised objective-c doesn't warn by default if you try to a potentially lossy conversion without an explicit cast.


I think it all depends what you meant by wider. I don't think anything will happen if you convert int8 to int16 (don't know swift so I don't know if it distinguishes between those types), but if you for example do casting from integer to floats and vice versa (the author uses double as the universal type) and do some heavy calculations you can get wrong results.

This is because float/double is not really a wider type it is just a number representation that is not exact and just uses approximations so you actually are losing information.


I'd generally limit wider to apply to the same, uh, type classes (there's probably a proper word) int8 to int16, float to double and so on.

Casting between integers and floating point is pretty risky unless you're absolutely sure about your ranges and precision. Anything that does that silently gives me The Fear.


> "I'm quite surprised objective-c doesn't warn by default if you try to a potentially lossy conversion without an explicit cast."

Implicit casts that are precision-lossy (say, int32 to int16) are definitely warnings in Obj-C, the issue is that most(?) Obj-C devs sail right past said warnings, and most projects are not configured to flag these as errors instead.

One of the other issues with implicit casts is that it's often non-obvious if what you're doing is lossy - there are a lot of aliased or conditional types (for example: a CGFloat is a float on 32-bit systems, and double on 64-bit)

Also things like time measurement - a NSTimeInterval is a double, so casting it down to a float is lossy, but not obviously so because for the most part we don't think about what's the actual object backing a lot of system types.




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

Search: