Brian Schroer

Don't Call Me Mort!

  Home  |   Contact  |   Syndication    |   Login
  30 Posts | 0 Stories | 22 Comments | 10 Trackbacks

News

Tag Cloud


Archives

Post Categories

Links

 fahrenheit = centigrade * 9 / 5 + 32;

How is the C# statement above evaluated?

  1. fahrenheit = (centigrade * 9) / (5 + 32);
  2. fahrenheit = centigrade * (9 / 5) + 32;
  3. fahrenheit = (centigrade * (9 / 5) + 32;
  4. fahrenheit = ((centigrade * 9) / 5) + 32;
  5. 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.

posted on Friday, February 03, 2006 7:41 AM

Feedback

# re: Operator precedence and rules of associativity 2/3/2006 7:46 AM Robert May
Oh how I wish that programmers would remember this rule--just use the stinking parenthesis and we'll all be happy! I've had to fix many bugs where precedence was ignored. Thanks for the post.

# re: Operator precedence and rules of associativity 2/3/2006 12:19 PM ajwarnock
But you forgot the bitwise operators... :-)
BUT keep on the SOAPBOX...

# re: Operator precedence and rules of associativity 2/3/2006 2:30 PM Peter Stathakos
Amen to that. Use the parenthesis and save everyone a heck of alot of trouble down the road.

Post Feedback

Title:
Name:
Email: (never displayed)
Url:
Comments: 
Please add 3 and 6 and type the answer here: