C++ Why we add parenthesis around assignments in if statements
05 January, 2026
Time to read: 1 mins
Last update: 05 January, 2026
I made a note for the question in the title back in 2022, but I always forget the answer.
From C++ Primer, 5th edition 2013, 4.4 “Assignment Operators” (p.146):
Because assignment (
=) has lower precedence than the relational operators (<><=, etc.), parentheses are usually needed around assignments in conditions.
int i;
while ((i = get_value()) != 42) {
// do something . . .
}You can verify it with man pages:
$ apropos associativity
associativity: nothing appropriate.
$ apropos preced
operator (7) - C operator precedence and order of evaluation
precedence (7) - C operator precedence and order of evaluation
$ man 7 operator
...
NAME
operator - C operator precedence and order of evaluation
DESCRIPTION
This manual page lists C operators and their precedence in evaluation.
Operator Associativity Notes
[] () . -> ++ -- left to right [1]
++ -- & * + - ~ ! sizeof right to left [2]
(type) right to left
* / % left to right
+ - left to right
<< >> left to right
< > <= >= left to right
== != left to right
& left to right
^ left to right
| left to right
&& left to right
|| left to right
?: right to left
= *= /= %= += -= <<= >>= &= ^= |= right to left
, left to rightAlso an extra bit from C++ Primer p.145
The result of an assignment is its left-hand operand, which is an lvalue. The type of the result is the type of the left-hand operand. If the types of the left and right operands differ, the right-hand operand is converted to the type of the left.
Other things to read
Popular
- Reveal animations on scroll with react-spring
- Gatsby background image example
- Extremely fast loading with Gatsby and self-hosted fonts