In Objective-C, is it a clean/safe approach to type cast let's say, a floating-point number to an integer with just assigning the floating-point variable to the int variable, and with the format specifier %i in NSLog call?
The proper way to do this is declaring the type cast like this:
int x;
float y;
y = 7.43;
x = (int) y; //type cast (int)
NSLog(@"The value of x is %i", x);
Output:
The value of x is 7
This type-casting method would be the ideal approach, but I tried to just assign the floating-point variable into the int variable and it works the same, is there a difference?
This is the other method without the (type-cast):
int x;
float y;
y = 7.43;
x = y; // no (int) casting for variable 'y' here
NSLog(@"The value of x is %i", x);
Output:
The value of x is 7
As you can see, is the same result, what's the difference? both methods are good? which is cleaner?
NSLog(@"The value of x is %i", y);
expecting implicit conversion from float to int to occur -- it won't, and the result will be gibberish (if you don't actually cause a crash). It would be legit to doNSLog(@"The value of x is %i", (int) y);
, however. – Hot Licks