Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between precedence, associativity, and order?

This confusion arises as most people are trained to evaluate arithmetic expressions as per PEDMAS or BODMAS rule whereas arithmetic expressions in programming languages like C# do not work in the same way.

What are your takes on it?

like image 502
Codeslayer Avatar asked Sep 16 '08 09:09

Codeslayer


2 Answers

Precedence rules specify priority of operators (which operators will be evaluated first, e.g. multiplication has higher precedence than addition, PEMDAS).

The associativity rules tell how the operators of same precedence are grouped. Arithmetic operators are left-associative, but the assignment is right associative (e.g. a = b = c will be evaluated as b = c, a = b).

The order is a result of applying the precedence and associativity rules and tells how the expression will be evaluated - which operators will be evaluated firs, which later, which at the end. The actual order can be changed by using braces (braces are also operator with the highest precedence).

The precedence and associativity of operators in a programming language can be found in its language manual or specification.

like image 154
Matej Avatar answered Nov 14 '22 21:11

Matej


I am not sure there really is a difference. The traditional BODMAS (brackets, orders, division, multiplication, addition, subtraction) or PEDMAS (parentheses, exponents, division, multiplication, addition, subtraction) are just subsets of all the possible operations and denote the order that such operations should be applied in. I don't know of any language in which the BODMAS/PEDMAS rules are violated, but each language typically adds various other operators - such as ++, --, = etc.

I always keep a list of operator precedence close to hand in case of confusion. However when in doubt it is usually worth using some parentheses to make the meaning clear. Just be aware that parentheses do not have the highest precedence - see http://msdn.microsoft.com/en-us/library/126fe14k.aspx for an example in C++.

like image 37
benefactual Avatar answered Nov 14 '22 21:11

benefactual