This is probably something very simple but I’m not getting the results I’m expecting. I apologise if it’s a stupid question, I just don’t what to google for.
Easiest way to explain is with some code:
int var = 2.0*4.0;
NSLog(@"%d", 2.0*4.0);//1
NSLog(@"%d", var);//2
if ((2.0*4.0)!=0) {//3
NSLog(@"true");
}
if (var!=0) {//4
NSLog(@"true");
}
This produces the following output:
0 //1
8 //2
true //3
true //4
The one that I don’t understand is line //1. Why are all the others converting (I’m assuming the correct word is “casting”, please correct me if I’m wrong) the float into an int, but inside NSLog it’s not happening. Does this have something to do with the string formatting %d parameter and it being fussy (for lack of a better word)?
You’re telling NSLog that you’re passing it an integer with the
@"%d"format specifier, but you’re not actually giving it an integer; you’re giving it a double-precision floating-point value (8.0, as it happens). When you lie to NSLog, its behavior is undefined, and you get unexpected results like this.Don’t lie to NSLog. If you want to convert the result of
2.0*4.0to an integer before printing, you need to do that explicitly:If, instead, you want to print the result of
2.0*4.0as a double-precision floating-point number, you need to use a different format specifier:More broadly, this is true of any function that takes a variable number of arguments and some format string to tell it how to interpret them. It’s up to you to make sure that the data you pass it matches the corresponding format specifiers; implicit conversions will not happen for you.