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.

Welcome to ShikshaSanchar!

ShikshaSanchar is a simple and helpful learning platform made for students who feel stressed by exams, assignments, or confusing topics. Here, you can study with clarity and confidence.

Here, learning is made simple. Notes are written in easy English, filled with clear theory, code examples, outputs, and real-life explanations — designed especially for students like you who want to understand, not just memorize.

Whether you’re from school, college, or someone learning out of curiosity — this site is for you. We’re here to help you in your exams, daily studies, and even to build a strong base for your future.

Each note on this platform is carefully prepared to suit all levels — beginner to advanced. You’ll find topics explained step by step, just like a good teacher would do in class. And the best part? You can study at your pace, anytime, anywhere.

Happy Learning! – Team ShikshaSanchar