Cpp 3: Precedence & Associativity - Question 1

Task: Add Parentheses Where Appropriate
coding
cplusplus
compiler
Author

Tony Phung

Published

September 3, 2025

1. Question 1: x = 3 + 4 + 5

Task:

  • Given a set of expressions that have no parentheses.
  • Using the operator precedence and associativity rules:
    • add parentheses to each expression
    • to make it clear how the compiler will evaluate the expression.

Reference:

2. Tp Solution

2.1 Operator: Precedence Level & Associativity

Operator ‘\(+\)’:

  • Precedence: \([3]\)
  • Associativity: \([L \to R]\)

Operator ‘\(=\)’:

  • Precedence: \([16]\)
  • Associativity: \([L \leftarrow R]\)

2.2 Workout

\[x = 3 + 4 + 5;\] \[x_{16} = {}_{16}3_{3} + {}_{3}4_{3} + {3}_5\] \[x_{16} = {}_{16}(3_{3} + {}_{3}4)_{3} + {3}_5\] \[x_{16} = {}_{16}(3+4)_{3} + {}_{3}5\] \[x_{16} = {}_{16}((3+4)_{3} + {}_{3}5)\] \[x_{16} = {}_{16}((3+4)+5)\] \[x_{16} = {}_{16}((3+4)+5)\] \[(x=((3+4)+5))\]