Is it clean/safe to type cast just with the format specifier and assignment operator in Objective-C?

StackOverflow https://stackoverflow.com/questions/19756983

سؤال

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?

هل كانت مفيدة؟

المحلول

You do not need the explicit cast, but it cannot hurt and it will make your code more readable.

I believe this is safe, mainly because the maximum float is much smaller than a possible int, so there should be no data loss.

Make sure your intention is truncating the decimal part of your float value rather than rounding.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top