Conditional (Ternary) Operator in C++
The Conditional Operator (?:) is a shorthand way of writing if-else statements in C++. It is also known as the Ternary Operator because it works with three operands.
It is mainly used to make the code shorter and more readable.
Syntax:
condition ? expression1 : expression2;
- condition → Expression to be checked
- expression1 → Executes if condition is true
- expression2 → Executes if condition is false
How Conditional (Ternary) Operator Works in C++
- If the condition is true, expression1 is executed.
- If the condition is false, expression2 is executed.
Example 1: Find Maximum Number
#include <iostream>
using namespace std;
int main()
{
int a = 10, b = 20;
int max = (a > b) ? a : b;
cout << "Maximum = " << max;
return 0;
}
Output:
Maximum = 20
Explanation:
- a = 10, b = 20
- Check condition → (a > b)
- 10 > 20 is false
- In ternary operator, when condition is false, the second value is selected
- So, value of b (20) is assigned to max
- Final Output → Maximum = 20
Example 2: Check Even or Odd
#include <iostream>
using namespace std;
int main()
{
int num = 7;
(num % 2 == 0) ? cout << "Even" : cout << "Odd";
return 0;
}
Output:
Odd
Explanation:
- num = 7
- Check condition → (num % 2 == 0)
- 7 % 2 gives 1, so the condition is false
- In ternary operator, when condition is false, the second value is selected
- So, "Odd" is printed
Summary:
- ?: is called the Conditional (Ternary) Operator.
- It is a shortcut of if-else.
- Syntax → condition ? value1 : value2
- It uses three operands (condition, true part, false part).
- It makes code short and clean.
- Best for simple conditions.
- Improves code readability for small conditions.
- Note: Avoid using ternary operator for complex conditions.