tags:

views:

30

answers:

2

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"???

A: 

If there were no parenthesis, the (int) would apply to only the first object parsed after that declaration, which in this case would be only slider, not slider.value.

Also, correct me if I'm wrong, but don't UISliders only go from 0.0 to 1.0? Getting an int value from this is pretty useless (0 or 1), right?

pop850
'.' (member) has highest precedence while (cast) has 2nd highest - so the (int) would apply to slider.value, not just slider, if the parentheses were omitted.
Adam Eberbach
A: 
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

int amount = (int)(slider.value);

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

int amount = (int)slider.value;

You can use

int amount = slider.value;

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.

Adam Eberbach