...
In this case, the programmer expects that the rightmost subexpression would evaluate first because of the greater precedence of the operator '*' as compared to than the operator '+' or '>'. The parenthesis parentheses reinforce this belief. These ideas lead to the incorrect conclusion that the right hand side will evaluate to zero whenever the get()
method returns zero. The test in the left hand subexpression should ideally reject the unprivileged user as the expected rating value is below the threshold of 10
(expecting number
= 0, due to number=get()
). Ironically, the program grants access to the unauthorized user. The reason is that evaluation of side-effect infested subexpressions follows the left to right ordering rule and should not be confused with the tenets of operator precedence, associativity and indicative parenthesisparentheses.
Code Block | ||
---|---|---|
| ||
class BadPrecedence { public static void main(String[] args) { int number=17; int[] threshold = new int[20]; threshold[0] = 10; number = (number > threshold[0]? 0:-2) + ((31 * ++number) * (number=get())); // ... if(number == 0) System.out.println("Access granted"); else System.out.println("Denied access"); // number = -2 } public static int get() { int number=0; // assign number to non zero value if authorized else 0 return number; } } |
...