Why is the type defined twice when using floor () in C?
I am trying to learn C / Objective-C. In this book I go through (Objective-C Programming: The Big nerd Ranch Guide) they set the type twice in this variable. What for? When I delete (unsigned int)
on the right side of the statement, it still works.
unsigned int feet = (unsigned int)floor(rawFeet);
source to share
It is incorrect to say that the type is defined twice. Defining a type means creating a new type. The type is mentioned twice here. On the left side, it is used to define a variable with a feet
type name unsigned int
. On the right it is used to express the return value floor
that returns double
, in unsigned int
- to assign a variable.
One-way note: if you know rawFeet is positive, which I would assume with unsigned, then the call is halfway unnecessary. Instead, you can just pass rawFeet to unsigned int.
eg.
double rawFeet = 24.6;
unsigned int feet = (unsigned int)rawFeet;
// feet now equals 24
Also, it was mentioned in the comments that the cast is not needed. This may be true, but many compilers will correctly provide you with a warning about this. In Visual C ++, for example:
unsigned int feet = floor(rawFeet);
// warning C4244: 'initializing' : conversion from 'double' to 'unsigned int', possible loss of data
source to share