Precedence and Associativity

 

See my Web Site, C++ Tutorial for the complete list of operators and their associativity and precedence.

 

Associativity also means “order of evaluation”.

 

Several operators in an expression may have equal precedence. In what order should the operations be conducted? The answer is “associativity”. The associativity of the operators having equal precedence tells you whether to perform the operations Right to Left or Left to Right.

 

Example of Precedence:

 

total = price – discount * salestax;

 

Should the multiplication take place first, or should the subtraction of discount from price take place first. The table of precedence tells us that multiplication has higher precedence – so the order of operations is as if the expression were written as follows:

 

total = price – (discount * salestax);

 

The parens are not needed here, but if used, they can override the intrinsic precedence of the operators and are often used when not needed just to clarify the intent.

 

You can force the precedence to be different by adding parens as follows:

total = (price – discount) * salestax;

[Don’t try to make any logical interpretation of these examples, because they are not very realistic.]

 

Example of Associativity:

 

total = price – discount + surcharge;

 

In the above statement discount is subtracted from price giving an intermediate result. Then the surcharge is added to that intermediate result giving the final result to be assigned to total.

Using values of 1.00, 0.10 and 0.05 as price, discount and surcharge, the total would be 0.95.

 

If, however, you intend that the discount and surcharge be added together before they are subtracted from price, you would force the order of the operations by using parenthesis, as follows:

 

total = price – {discount + surcharge);

 

The total would now be  0.85 – quite a different result, because now the surcharge has been effectively subtracted from the final price, rather than added to it.

 

Beware!

 

Sometimes the operations DO NOT COMPLETE.

The && and || operators evaluate the expressions starting with the leftmost one. As soon as the truth of the total expression is guaranteed, the expression evaltuaion stops. This means expressions with side effects may not be evaluated and the side effects might not be realized. Consider:

If (moredata() || moretime())

        // . . .

 

If the moredata() function returns true, then the moretime() function is not even called.