C++ Conditional Operator

The Conditional Operator in C++ is a shorthand way of writing an if…else statement. It is also known as the ternary operator because it uses three operands. This operator is useful when you want to make simple decisions and return a value based on a condition.

Syntax

condition ? expression1 : expression2;

If the condition is true, expression1 is executed. If the condition is false, expression2 is executed.

Example Program

#include <iostream>
using namespace std;

int main() {

    int a = 10;
    int b = 20;

    int max = (a > b) ? a : b;

    cout << "Maximum number is: " << max;

    return 0;
}

Output

Maximum number is: 20

Equivalent If-Else Statement

The same logic using an if…else statement would look like this:

int max;

if(a > b) {
    max = a;
} else {
    max = b;
}

Common Uses of Conditional Operator

  • Selecting the larger or smaller value between two numbers.
  • Assigning values based on simple conditions.
  • Reducing the number of lines in simple decision-making code.

Important Notes

  • The conditional operator is best used for simple conditions.
  • It improves code readability when used properly.
  • For complex logic, using a normal if…else statement is usually better.

Next Topic

Next, learn about C++ For Loop.