Geeks With Blogs
Brian Schroer Don't Call Me Mort!
 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 3, 2006 7:41 AM .NET | Back to top


Comments on this post: Operator precedence and rules of associativity

# re: Operator precedence and rules of associativity
Requesting Gravatar...
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.
Left by Robert May on Feb 03, 2006 7:46 AM

# re: Operator precedence and rules of associativity
Requesting Gravatar...
But you forgot the bitwise operators... :-)
BUT keep on the SOAPBOX...
Left by ajwarnock on Feb 03, 2006 12:19 PM

# re: Operator precedence and rules of associativity
Requesting Gravatar...
Amen to that. Use the parenthesis and save everyone a heck of alot of trouble down the road.
Left by Peter Stathakos on Feb 03, 2006 2:30 PM

# re: Operator precedence and rules of associativity
Requesting Gravatar...
Hej,
This is just my second week into reading Perl. I learnt of BODMASS at primary school, does this apply with the operators?

Cheers
Left by Kim on Apr 12, 2010 8:56 AM

Your comment:
 (will show your gravatar)


Copyright © Brian Schroer | Powered by: GeeksWithBlogs.net