The conditional (ternary) operator ? :
has relatively low precedence compared to most other operators in C++. It has lower precedence than the arithmetic, comparison, and bitwise operators, but higher precedence than the assignment and comma operators.
This means that expressions involving the conditional operator may need to be parenthesized to ensure the desired evaluation order. For example:
#include <iostream>
int main() {
int x{5}, y{10};
// This is evaluated as (1 + false) ? 2 : 3
// Which becomes true ? 2 : 3
// Which becomes 2
int result1 = 1 + false ? 2 : 3;
std::cout << "result1: " << result1 << "\n";
// This is evaluated as 1 + (false ? 2 : 3)
// Which becomes 1 + 3
// Which becomes 4
int result2 = 1 + (false ? 2 : 3);
std::cout << "result2: " << result2 << "\n";
}
result1: 2
result2: 4
In the first case, result1
is incorrectly evaluated as (1 + 0) ? 2 : 3)
due to operator precedence, resulting in 2
. In the second case, result2
is correctly evaluated as intended, yielding 4.
To avoid confusion and ensure clarity, it's generally a good practice to use parentheses when combining the conditional operator with other operators in complex expressions. This can include adding superfluous parentheses - even if they don’t change the behaviour of the expression, they can sometimes make the expression easier to understand.
Answers to questions are automatically generated and may not have been reviewed.
Learn the fundamentals of controlling program flow in C++ using if statements, for loops, while loops, continue, and break