posted 20 years ago
I have come across following question from Dan's operator section tests:
________________________________________________________________________
What is the result of attempting to compile and run the above program?
a. Prints: false,false,false
b. Prints: false,false,true
c. Prints: false,true,false
d. Prints: false,true,true
e. Prints: true,false,false
f. Prints: true,false,true
g. Prints: true,true,false
h. Prints: true,true,true
i. Runtime error
j. Compiler error
k. None of the above
__________________________________________________________________________
Now, based on the operator precedence and operator evaluation rules, '&&' has got a higher precedence than '||'. So, according to me, these should be the order of steps executed at runtime:
b is assigned a true valueSince b is true, the short-circuit &&operator has to evaluate second operand, i.e. cc is assigned a true valueThe result of && operand is trueNow, the || operator is evaluated. a is assigned a true value.Since a is already true, it returns the value of expression as trueNow, x is assigned a true value.
Based on this logic, the answer to this question should be 'h' while the correct answer is 'e'. (I have checked it with compiler too). Now, it looks like the operators are being evaluated from left to right but that should only occur when two operators are of equal precedence.
Why is it behaving this way? If its always supposed to behave this way, what does the higher precedence of && to || imply? When does it usually come into action? Please support with an example.
Thanks,
Nidhi.