Operator precedence tells only part of the story when determining the order in which to apply operators. What happens when all of your operators have the same precedence as in the following example?
If the leftmost subtraction is performed first, then the expression evaluates to8 - 4 - 2
If the rightmost subtraction is performed first, then the expression evaluates to(8 - 4) - 2 ⇒ 4 - 2 ⇒ 2
Obviously, the order in which operators are applied determines the value of the expression. However, some characteristic other than precedence must be used when all the operators in the expression have the same precedence level.8 - (4 - 2) ⇒ 8 - 2 ⇒ 6
This new characteristic is called operator associativity. Associativity determines whether the operator associates from the left or from the right. In the example above, if subtraction is left- associative, then the compiler implicitly parenthesizes from left to right:
If subtraction is right-associative, then the compiler implicitly parenthesizes right to left:(8 - 4) - 2
8 - (4 - 2)
So, which is it? Try it out. Modify your program to output the result of the parenthesis-free expression and then compile and execute it.
Question #3.7.1: Is subtraction left- or right-associative?
Now, let's check out division:
8 / 4 / 2
Question #3.7.2: Write the equation with explicit parentheses if division were left-associative. What does it evaluate to?
Question #3.7.3: Write the equation with explicit parentheses if division were right-associative. What does it evaluate to?
Now modify your program to output the result of the parenthesis-free expression. Compile and execute your program.
Question #3.7.4: Is division left- or right-associative?
Check out addition:
8 + 4 + 2
Question #3.7.5: Write the equation with explicit parentheses if addition is left-associative. What does it evaluate to?
Question #3.7.6: Write the equation with explicit parentheses if addition is right-associative. What does it evaluate to?
So, for some operations it doesn't appear to matter.
Based on these experiments, you may wonder whether all of the arithmetic, relational, and logic operators are left-associative. This is, in fact, the case.
Also, it should be evident that the output operator
is also left-associative. Consider this output statement:
There are three objects that are printed to the screen, a string, an integer, and a newline.cout << "i is " << i << endl;
Question #3.7.7: What is printed first? What is printed second? What is printed last?
Whatever is done first should have the first set of implicit parentheses around it.
Question #3.7.8: How would you parenthesize the output statement?
You should be able to find a complete list of operator precedence and associativity in any C++ textbook or online.
Some operators do associate to the right, the most common being the assignment operator (see Experiment #9).