Lesson 21 of 60 – Conditional Operator in C++
35%

Conditional Operator in C++

The conditional operator is a special operator used to choose one of two values or expressions based on a condition. It is also called the ternary operator because it uses three operands.

Note: The conditional operator uses the syntax condition ? expression1 : expression2. If the condition is true, the first expression is selected; otherwise, the second expression is selected.

1. What is the Conditional Operator?

The conditional operator is used to make a simple decision in a single expression.

int age = 20;

int result = (age >= 18) ? 1 : 0;

Since the condition is true, result becomes 1.

2. Why is it Called Ternary Operator?

The conditional operator is called a ternary operator because it works with three operands:

  • A condition
  • The expression used when the condition is true
  • The expression used when the condition is false
condition ? trueValue : falseValue;

3. Syntax of Conditional Operator

The basic syntax is:

condition ? expression1 : expression2;

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

4. Simple Example

int age = 20;

std::string result =
    (age >= 18) ? "Adult" : "Minor";

The condition age >= 18 is true, so result becomes "Adult".

5. Conditional Operator with Numbers

int a = 10;
int b = 20;

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

Since a > b is false, the value of b is selected. Therefore, larger becomes 20.

6. Finding the Smaller Number

int a = 10;
int b = 20;

int smaller = (a < b) ? a : b;

The condition is true, so smaller becomes 10.

7. Conditional Operator with Even and Odd

int number = 7;

std::string result =
    (number % 2 == 0) ? "Even" : "Odd";

The remainder is not zero, so the result is "Odd".

8. Checking Pass or Fail

int marks = 65;

std::string result =
    (marks >= 40) ? "Pass" : "Fail";

Because marks are at least 40, the result is "Pass".

9. Checking Positive or Negative

int number = -5;

std::string result =
    (number >= 0) ? "Positive or Zero" : "Negative";

The condition is false, so the result is "Negative".

10. Conditional Operator with bool

A Boolean condition can be used directly with the conditional operator.

bool isLoggedIn = true;

std::string message =
    isLoggedIn ? "Welcome" : "Please login";

The result is "Welcome".

11. Printing Directly

The selected result can be printed directly without storing it in another variable.

int age = 25;

std::cout <<
    ((age >= 18) ? "Adult" : "Minor");

12. Conditional Operator with User Input

#include <iostream>

int main() {

    int number;

    std::cout << "Enter a number: ";
    std::cin >> number;

    std::cout <<
        ((number > 0) ? "Positive" : "Zero or Negative");

    return 0;
}

13. Conditional Operator with Character

char grade = 'A';

std::string result =
    (grade == 'A') ? "Excellent" : "Other Grade";

If the grade is A, the first expression is selected.

14. Conditional Operator with String

#include <iostream>
#include <string>

int main() {

    std::string name = "Rahul";

    std::string message =
        (name == "Rahul") ? "Name matched" : "Name did not match";

    std::cout << message;

    return 0;
}

15. Conditional Operator vs if-else

A simple conditional assignment can often be written using either if-else or the conditional operator.

Using if-else:

int age = 20;
std::string result;

if (age >= 18) {
    result = "Adult";
} else {
    result = "Minor";
}

Using conditional operator:

std::string result =
    (age >= 18) ? "Adult" : "Minor";

16. Finding the Greater of Two Numbers

int a = 45;
int b = 30;

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

std::cout << "Greater = " << greater;

The result is 45.

17. Finding the Smaller of Two Numbers

int a = 45;
int b = 30;

int smaller = (a < b) ? a : b;

std::cout << "Smaller = " << smaller;

The result is 30.

18. Checking Voting Age

int age = 22;

std::string result =
    (age >= 18) ? "Eligible by age" : "Not eligible by age";

The condition checks whether the age is at least 18.

19. Checking Temperature

double temperature = 35.5;

std::string result =
    (temperature > 30) ? "Hot" : "Normal";

Since the temperature is greater than 30, the result is "Hot".

20. Conditional Operator with Calculations

int a = 20;
int b = 10;

int result = (a > b) ? a - b : b - a;

The condition is true, so a - b is selected and the result is 10.

21. Nested Conditional Operator

A conditional operator can be nested inside another conditional operator. However, excessive nesting can make code difficult to read.

int marks = 75;

std::string result =
    (marks >= 80) ? "A" :
    (marks >= 60) ? "B" :
    (marks >= 40) ? "C" : "F";

For complex decisions, an if-else if structure is often easier to understand.

22. Conditional Operator with Multiple Conditions

The condition can contain logical operators.

int age = 25;
bool hasID = true;

std::string result =
    (age >= 18 && hasID)
    ? "Allowed"
    : "Not Allowed";

Both conditions must be true for the first result to be selected.

23. Conditional Operator with Decimal Values

double price1 = 100.50;
double price2 = 150.75;

double lower =
    (price1 < price2) ? price1 : price2;

The smaller price is stored in lower.

24. Conditional Operator and Assignment

The conditional operator is frequently used on the right side of an assignment.

int number = 10;

int absoluteValue =
    (number >= 0) ? number : -number;

If the number is negative, its negative value is selected to produce a non-negative result.

25. Conditional Operator Return Type

The two result expressions participate in determining the type of the conditional expression. Therefore, when the two expressions have different types, C++ may perform the appropriate conversions.

int age = 20;

double result =
    (age >= 18) ? 100.0 : 50.0;

Both possible results here are double values.

26. Conditional Operator with Function Calls

The selected expression can also contain a function call.

#include <iostream>

void showAdult() {
    std::cout << "Adult";
}

void showMinor() {
    std::cout << "Minor";
}

int main() {

    int age = 20;

    (age >= 18) ? showAdult() : showMinor();

    return 0;
}

Only the selected expression is evaluated.

27. Practical Discount Example

#include <iostream>

int main() {

    double purchase = 1500;

    double discount =
        (purchase >= 1000) ? 10.0 : 0.0;

    std::cout << "Discount: "
              << discount << "%";

    return 0;
}

The program assigns a 10% discount when the purchase amount is at least 1000.

28. Complete Conditional Operator Example

#include <iostream>
#include <string>

int main() {

    int marks;

    std::cout << "Enter marks: ";
    std::cin >> marks;

    std::string result =
        (marks >= 40) ? "Pass" : "Fail";

    std::cout << "Result: " << result
              << std::endl;

    std::string status =
        (marks >= 75) ? "Good Score" : "Regular Score";

    std::cout << "Status: " << status;

    return 0;
}

29. Common Conditional Operator Mistakes

  • Forgetting the : between the two result expressions.
  • Writing a conditional operator without a valid condition.
  • Confusing ? with other operators.
  • Using too many nested conditional operators and making code difficult to read.
  • Forgetting that the operator selects one of two expressions.
  • Using if-else when a complex block of statements is required.
  • Ignoring possible type conversions between the two result expressions.

30. Conditional Operator – Final Summary

Part Meaning Example
Condition Checks whether something is true or false age >= 18
? Starts the true expression ?
True expression Selected when condition is true "Adult"
: Separates true and false expressions :
False expression Selected when condition is false "Minor"
condition ? trueExpression : falseExpression;

📌 Key Points

  • The conditional operator is also called the ternary operator.
  • Its syntax is condition ? expression1 : expression2.
  • It provides two possible result expressions.
  • The first expression is selected when the condition is true.
  • The second expression is selected when the condition is false.
  • It is useful for short and simple decisions.
  • It can be used with numbers, strings, characters, Boolean values, and expressions.
  • It can be combined with logical operators.
  • Nested conditional operators are possible but can reduce readability.
  • For complex decision-making, if-else may be easier to understand.

🧠 Quick Quiz

Question: What is the output of the following C++ code?

int a = 10;
int b = 20;

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