Changes

Objective-C Operators and Expressions

2,195 bytes removed, 14:45, 7 October 2009
C# Operator Precedence
Whilst the above code is perfectly valid it is important to be aware that Objective-C does not evaluate the expression from left to right or right to left, but rather in an order specified by the precedence of the various operators. ''Operator precedence'' is an important topic to understand since it impacts the result of a calculation and will be covered in detail the chapter entitled [[Objective-C 2.0 Operator Precedence]].
== C# Operator Precedence ==
When humans evaluate expressions, they usually do so starting at the left of the expression and working towards the right. For example, working from left to right we get a result of 300 from the following expression:
 
10 + 20 * 10 = 300
 
This is because we, as humans, add 10 to 20, resulting in 30 and then multiply that by 10 to arrive at 300. Ask C# to perform the same calculation and you get a very different answer:
 
<pre>
int x;
 
x = 10 + 20 * 10;
 
System.Console.WriteLine (x)
</pre>
 
The above code, when compiled and executed, will output the result 210.
 
This is a direct result of ''operator precedence''. C# has a set of rules that tell it in which order operators should be evaluated in an expression. Clearly, C# considers the multiplication operator (*) to be of a higher precedence than the addition (+) operator.
 
Fortunately the precedence built into C# can be overridden by surrounding the lower priority section of an expression with parentheses. For example:
 
<pre>
int x;
 
x = (10 + 20) * 10;
 
System.Console.WriteLine (x)
</pre>
 
In the above example, the expression fragment enclosed in parentheses is evaluated before the higher precedence multiplication resulting in a value of 300.
 
The following table outlines the C# operator precedence order from highest precedence to lowest:
 
 
<table border="1" cellspacing="0">
<tr style="background:#efefef;">
<th>Precedence</th><th>Operators</th>
<tr>
<td>Highest<td>+ - ! ~ ++x --x (T)x</td>
<tr>
<td><td>* / %</td>
<tr>
<td><td>+ -</td>
<tr>
<td><td><< >></td>
<tr>
<td><td>< > <= >= is as</td>
<tr>
<td><td>== !=</td>
<tr>
<td><td>&</td>
<tr>
<td><td>^</td>
<tr>
<td><td>|</td>
<tr>
<td><td>&&</td>
<tr>
<td><td>||</td>
<tr>
<td><td>:?</td>
<tr>
<td>Lowest<td>= *= /= %= += -= <<= >>= &= ^= |=</td>
<table>
<br>
 
It should come as no surprise that the assignment operators have the lowest precedence since you would not want to assign the result of an expression until that expression had been fully evaluated.
 
Don't worry about memorizing the above table. Most programmers simply use parentheses to ensure that their expressions are evaluated in the desired order.
== Compound Assignment Operators ==