• Home
  • 3.20 Conditional Operator (?:)

3.20 Conditional Operator (?:)

View Categories

3.20 Conditional Operator (?:)

1 min read

Table of Contents

The conditional operator (?:), also known as the ternary operator, evaluates a condition and returns one of two expressions depending on whether the condition is true or false. It provides a compact alternative to a simple if-else statement.

The conditional operator consists of three operands: a condition, an expression evaluated when the condition is true, and another expression evaluated when the condition is false.

Source Code #

#include <iostream>

int main()
{
    int num1 = 25;
    int num2 = 40;

    int maximum = (num1 > num2) ? num1 : num2;

    std::cout << "First Number : " << num1 << '\n';
    std::cout << "Second Number: " << num2 << '\n';
    std::cout << "Maximum      : " << maximum << '\n';

    return 0;
}

Output #

First Number : 25
Second Number: 40
Maximum      : 40

Explanation #

  • The conditional operator (?:) evaluates a Boolean condition.
  • The syntax of the operator is condition ? expression1 : expression2.
  • If the condition evaluates to true, the first expression is evaluated and its value becomes the result.
  • If the condition evaluates to false, the second expression is evaluated and its value becomes the result.
  • (num1 > num2) ? num1 : num2 returns the larger of the two numbers.
  • The returned value is assigned to the variable maximum.
  • The conditional operator is commonly used for simple decision-making expressions where a full if-else statement is unnecessary.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *