Conditionals and Loops

# 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.

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

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:

• 124 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.