Conditionals and Loops

Conditional Operator Precedence

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

Abstract art representing computer programming

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.

This Question is from the Lesson:

Conditionals and Loops

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

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Conditionals and Loops

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

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved