Cpp 4: Precedence & Associativity - Question 2 to 4

Task: Add Parentheses Where Appropriate
coding
cplusplus
compiler
Author

Tony Phung

Published

September 3, 2025

1. Task & References

Q2: x = y = z;

2.1 Soln: Precedence Level & Associativity

Operator Precedence Level Associativity
\(=\) \(16\) \([L \leftarrow R]\)

2.2 Soln: Workout

\[x = y = z;\] \[x_{16} = {}_{16}y_{16} = {}_{16}z;\] \[x_{16} = {}_{16}(y_{16} = {}_{16}z);\] \[x_{16} = {}_{16}(y=z);\] \[(x_{16} = {}_{16}(y=z));\] \[(x = (y=z));\]

Q3: z *= ++y + 5;

3.1 Soln: Precedence Level & Associativity

c++ Operator Precedence Level Associativity Description
*= \(16\) \([L \leftarrow R]\) Multiplication assignment
++ \(3\) \([L \leftarrow R]\) Prefix increment (++y)
- opposed to y++
- i.e. Suffix increment
- i.e. \([2: L \to R]\)
+ \(6\) \([L \leftarrow R]\) Unary plus

3.2 Soln: Workout

\[z \texttt{ *=} \texttt{ ++}y + 5;\] \[z_{[16]} \texttt{ *= }_{[16]}\texttt{++}{}_{[3]}y_{[6]} + {}_{[6]}5;\] \[z_{[16]} \texttt{ *= }_{[16]}(\texttt{++}{}_{[3]}y)_{[6]} + {}_{[6]}5;\] \[z_{[16]} \texttt{ *= }_{[16]}(\texttt{++}y)_{[6]} + {}_{[6]}5;\] \[z_{[16]} \texttt{ *= }_{[16]}((\texttt{++}y)_{[6]} + {}_{[6]}5);\] \[z_{[16]} \texttt{ *= }_{[16]}((\texttt{++}y) + 5);\] \[(z \texttt{ *= }((\texttt{++}y) + 5));\]

Q4: a || b&&c || d;

4.1 Soln: Precedence Level & Associativity

c++ Operator Precedence Level Associativity Description
|| \(15\) \([L \to R]\) Logical OR (also or)
&& \(14\) \([L \to R]\) Logical AND (also and)

4.2 Soln: Workout

\[a_{[15]}{}_{[15]}\texttt{ || }_{[15]}{}_{[15]}b_{[14]}{}_{[14]}\&\&_{[14]}{}_{[14]}c_{[15]}{}_{[15]}\texttt{ || }_{[15]}{}_{[15]}d;\] \[a_{[15]}{}_{[15]}\texttt{ || }_{[15]}{}_{[15]}(b_{[14]}{}_{[14]}\&\&_{[14]}{}_{[14]}c)_{[15]}{}_{[15]}\texttt{ || }_{[15]}{}_{[15]}d;\] \[a_{[15]}{}_{[15]}\texttt{ || }_{[15]}{}_{[15]}(b\&\&c)_{[15]}{}_{[15]}\texttt{ || }_{[15]}{}_{[15]}d;\] \[(a_{[15]}{}_{[15]}\texttt{ || }_{[15]}{}_{[15]}(b\&\&c))_{[15]}{}_{[15]}\texttt{ || }_{[15]}{}_{[15]}d;\] \[(a||(b\&\&c))_{[15]}{}_{[15]}\texttt{ || }_{[15]}{}_{[15]}d;\] \[((a||(b\&\&c))_{[15]}{}_{[15]}\texttt{ || }_{[15]}{}_{[15]}d);\] \[((a||(b\&\&c))d);\]