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...
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...
C supports implicit casting, and you will also get a warning if size_t is less precise than CGSize for some reason.
You should use the proper type, which is probably CGFloat. size_t is something int'ish and inappropriate.
A cast is usually not needed (and sometimes wrong).
C
does the "right thing" most of the time.
In your case, the cast is not needed (but not wrong, merely redundant).
You need to cast
printf("%p\n", (void*)some_pointer)
is*()
(isdigit, isblank, ...) and toupper()
and tolower()
if (isxdigit((unsigned char)ch)) { /* ... */ }
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?
The size_t
type is for something completely different, you should not use it for such purposes.
Its purpose is to express the sizes of different types in memory. For example, the sizeof(int)
is of type size_t
and it returns the size of the int
type.
As the others suggested, use the appropriate type for that variable.