size_t pixelsWidth = (size_t)bitmapSize.width;
Or is it totally fine to do without the casting to size_t? bitmapSize is of type CGSize...
You should use the proper type, which is probably CGFloat. size_t is something int'ish and inappropriate.
In this case, the type of bitmapSize.width
is CGFloat
(currently float
on iPhone).
Converting from float
to size_t
has undefined behavior (according to the C standard - not sure whether Apple provides any further guarantees) if the value converted doesn't fit into a size_t
. When it does fit, the conversion loses the fractional part. It makes no difference whether the conversion is implicit or explicit.
The cast is "good" in the sense that it shows, in the code, that a conversion takes place, so programmers reading the code won't forget. It's "bad" in the sense that it probably suppresses any warnings that the compiler would give you that this conversion is dangerous.
So, if you're absolutely confident that the conversion will always work then you want the cast (to suppress the warning). If you're not confident then you don't want the cast (and you probably should either avoid the conversion or else get confident).
In this case, it seems likely that the conversion is safe as far as size is concerned. Assuming that your CGSize object represents the size of an actual UI element, it won't be all that big. A comment in the code would be nice, but this is the kind of thing that programmers stop commenting after the fiftieth time, and start thinking it's "obvious" that of course an image width fits in a size_t
.
A further question is whether the conversion is safe regarding fractions. Under what circumstances, if any, would the size be fractional?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With