fahrenheit = centigrade * 9 / 5 + 32;
How is the C# statement above evaluated?
- fahrenheit = (centigrade * 9) / (5 + 32);
- fahrenheit = centigrade * (9 / 5) + 32;
- fahrenheit = (centigrade * (9 / 5) + 32;
- fahrenheit = ((centigrade * 9) / 5) + 32;
- fahrenheit = centigrade * (9 / (5 + 32));
The correct answer is 4, but please “don't make me think“ when coding math expressions. If your programming language allows parentheses (and I don't know of one that doesn't), why not use them to make the order explicit and to make the code a lot more readable:
fahrenheit = ((centigrade * 9) / 5) + 32;
Why assume that both you and someone reading the code later remember the rules correctly?
For the record, here is the order of precedence, so I can refer to it when I come across code written by someone who thinks parentheses are for wimps:
| Category |
Operators |
| Multiplicative |
* / % |
| Additive |
+ - |
| Equality |
== (equal), != (not equal) |
| Logical AND |
& |
| Logical XOR |
^ |
| Logical OR |
| |
| Conditional AND |
&& |
| Conditional OR |
|| |
| Conditional |
?: |
When two operators have the same precedence level (e.g. the multiplication and division operators in the statement centigrade * 9 / 5), the rules of associativity say that the leftmost operator gets precedence.
Print | posted on Friday, February 03, 2006 7:41 AM