Conditional Operator Precedence

What is the precedence of the conditional (ternary) operator compared to other operators?

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.

Conditionals and Loops

Learn the fundamentals of controlling program flow in C++ using if statements, for loops, while loops, continue, and break

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Using break in Nested Loops
How can I break out of nested loops using the break keyword?
Condition in a do-while Loop
Is it possible to have a condition that always evaluates to false in a do-while loop?
Short-Circuit Evaluation Order
In what order are the conditions evaluated in short-circuit evaluation?
Detecting Infinite Loops
How can I detect and prevent infinite loops in my C++ code?
Scope of Loop Variables
What is the scope of variables declared within the initialization statement of a for loop?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant