Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Is there an easy way to remember the operatos precedence?

maha anna
Ranch Hand
Posts: 1467
Can someone tell me a easy way to rembember the operator precedence.. It bugs me always when I see a code like the foll.
Who will write code like this in practice...? I am always used to put ( ) to ensure what I want the computer to do and make myself and other clear at ant time.

Assuming this code is there in a program what will be the val of n after n >>= 2; statement. How do we go about it.
Thank you.

CitySlicker
Greenhorn
Posts: 16
Take a look at operator precedence. You'll find that addition/mult/ are rather high and that boolean ops are low.
So here is how this code works:
<code>
int n=7;
n <<= 3;<br /> //56 becuase 7 to binary is 111 <br /> //now push 3 zeros from behind<br /> //111000 = 56 dec.<br /> n = n & n + 1 | n + 2 ^ n + 3;<br /> //addition is higher than boolean<br /> //so n &(n +1) | (n +2) ^ (n +3)<br /> // n & 59 | 58 ^ 59 (just start from left and go right)<br /> // n = 57<br /> n >>= 2;
//pushing in 2 zeros from left to right=
//111001 -> 001110 = 14
</code>
n is 14 in the end. I just kind of "memorize/visualize" op precedence.

maha anna
Ranch Hand
Posts: 1467
// n & 59 | 58 ^ 59 (just start from left and go right)
Step 1--> 111000 & 111011 | 111010 ^ 111011
Step 2--> 111000 | 111010 ^ 111011
Step 3--> 111010 ^ 111011
Step 4--> 000001
Gives 1 when we go from left to right. How did you get the ans diff. I think among bitwise | & ^ there is another precedence order.

Jim Yingst
Wanderer
Sheriff
Posts: 18671
If you compile and run, you will see that 14 is the correct answer. The order of precedence for bitwise operators is &, ^, | - "just start from left and go right" is incorrect. Here is a corrected calculation:
<code><pre>n = n & n + 1 | n + 2 ^ n + 3;
n = 56 & 57 | 58 ^ 59;
n = 56 & 57 | 58 ^ 59;
n = 111000 & 111001 | 111010 ^ 111011;
n = (111000 & 111001) | 111010 ^ 111011; // evaluate &
n = 111000 | (111010 ^ 111011); // evaluate ^
n = 111000 | 000001; // evaluate |
n = 111001;</pre></code>
And then:
<code><pre>n >>= 2;
n = 111001 >> 2;
n = 1110;
n = 14;</pre></code>
Here's a complete list of operator precedence:

1. ++, --, + (unary), - (unary), ~, !, and any cast
2. *, /, %
3. +, -
4. <<, >>, >>>
5. <, <=, >, >=, instanceof
6. ==, !=
7. &
8. ^
9. |
10. &&
11. | |
12. ?: (ternary)
13. =, *=, /=, %=, +=, -=, <<=, >>=, >>>=, &=, ^=, |=

14. Anything listed on the same line is equal precedence - evaluate left to right.

maha anna
Ranch Hand
Posts: 1467
Thank you Mr.Jim. I really appreciate your help.
regds. Now I have to remember all this...which is HAAAARD.
Maha Anna.

Gilbert Baron
Greenhorn
Posts: 23
Look at the Bruce Eckel Thinking in Java. He has a mnemonic.
Ulcer Unary