vietnguyen09 vietnguyen09 - 1 year ago 59
iOS Question

Objective-C What way of multiple conditions are right?

I have a condition like this

if(hour == TT_MB_HOUR && minutes >= 0 && minutes <= TT_MB_MINUTES_END){
return YES;

But I've seen somebody write like this

if((hour == TT_MB_HOUR) && (minutes >= 0) && (minutes <= TT_MB_MINUTES_END)){
return YES;

So, What way is right?

Answer Source

So, What way is right?

Both of them.

As in most programming languages (Objective-)C uses operator precedence to determine in what order to evaluate operators within an expression. Just in the same way you know that 3 + 4 * 5 evaluates to 23 (and not to 35) in maths.

The logical operators && and || are lower priority than the comparison operators so are performed after them.

If is it unclear in any situation a good rule of thumb is "when there might be doubt add parentheses" to make explicit what is implicit (and of course if you need to change the priority as in (3 + 4) * 5 which does evaluate to 35). The author of your code obviously felt the parentheses made it clearer, they are neither right or wrong - its an opinion.

Havard have a nice table of C operator precedence.