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…
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In this case, the type of
bitmapSize.widthisCGFloat(currentlyfloaton iPhone).Converting from
floattosize_thas undefined behavior (according to the C standard – not sure whether Apple provides any further guarantees) if the value converted doesn’t fit into asize_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?