Difference between revisions of "Objective-C 2.0 Operator Precedence"
m (Text replacement - "<google>ADSDAQBOX_FLOW</google>" to "<htmlet>adsdaqbox_flow</htmlet>") |
m (Text replacement - "<google>BUY_OBJC</google>" to "<htmlet>objc<htmlet>") |
||
Line 7: | Line 7: | ||
<hr> | <hr> | ||
− | < | + | <htmlet>objc<htmlet> |
In the previous chapter of [[Objective-C 2.0 Essentials]] we looked at Objective-C operators and expressions. An equally important area to understand is operator precedence. This is essentially the order in which Objective-C evaluates expressions comprising more than one operator. | In the previous chapter of [[Objective-C 2.0 Essentials]] we looked at Objective-C operators and expressions. An equally important area to understand is operator precedence. This is essentially the order in which Objective-C evaluates expressions comprising more than one operator. |
Revision as of 21:05, 1 February 2016
Previous | Table of Contents | Next |
Objective-C Operators and Expressions | Commenting Objective-C Code |
Operator | Description | Precedence | Associativity |
---|---|---|---|
[] |
access array element or message expression |
Highest | left to right |
++ |
increment |
right to left | |
* |
multiply |
left to right | |
+ |
add |
left to right | |
<< |
bitwise shift left |
left to right | |
<= |
less than or equal to |
left to right | |
== |
equality inequality |
left to right | |
& | bitwise AND | left to right | |
^ | bitwise XOR | left to right | |
| | bitwise OR | left to right | |
&& | logical AND | left to right | |
|| | logical OR | left to right | |
?: | conditional | right to left | |
= += -= *= /= %= &= ^= |= <<= >>= >>>= |
assignment |
right to left | |
, |
comma |
Lowest | right to left |
As we can see from the table, when operators from the same precedence level appear in an expression, the operators are evaluated either left to right or right to left depending on the associativity of that group. For example, the following expression will be evaluated left to right because both operators are in the same precedence level and this is the rule dictated by the corresponding associativity:
int x = 10 * 20 / 5;
Overriding Operator Precedence
The precedence and associativity rules built into Objective-C can be overridden by surrounding the lower priority section of an expression with parentheses. For example, we can override precedence and force a left to right evaluation of our original example as follows:
int x = (10 + 20) * 10; NSLog(@"Result is %i", x);
In the above example, the expression fragment enclosed in parentheses is evaluated before the higher precedence multiplication resulting in the expression equaling 300 instead of the 210 result we saw when we allowed precedence to take effect:
2009-10-09 11:42:43.845 t[5630] Result is 300
<google>BUY_OBJC_BOTTOM</google>
Previous | Table of Contents | Next |
Objective-C Operators and Expressions | Commenting Objective-C Code |