Why is it that in the following code:
-(IBAction)updateSlider:(id)sender {
UISlider *slider = (UISlider *) sender;
int amount = (int)(slider.value);
NSString *newText = [[NSString alloc]initWithFormat:@"%d", amount];
sliderLabel.text = newText;
newText.release;
}
the line “int amount = (int)(slider.value);” is the way it is? Why couldn’t it be simply “int amount = int slider.value”???
This isn’t legal C and has no meaning to the compiler, it will produce an error (Expected expression before ‘int’). The meaning of
is that an auto variable of type int named amount is being declared and assigned some value, being the integer cast of the floating point value of slider.value. The type of slider.value is float – you can assign a float to an int but you’ll get a warning. Using
(int)performs a cast from float to int, discarding the fractional part of the number.Cast has lower precendence than ‘.’ operator so you could also use
You can use
and ignore the warning. But since a slider’s default values are from 0.0 to 1.0 you might not want to do this, it probably won’t give you a useful result. Also because of the nature of the cast (discarding the fractional part) the result may always be zero. Floats can do some tricky things – if you’re comparing them or testing for equality for example you usually define an acceptable difference and see if they are that close, not absolutely equal.