C++ Ternary (Conditional) Operator

The ternary operator in C++ is a shorthand for simple if-else statements. It takes three operands and evaluates a condition, returning one value if true and another if false.

1. Basic Syntax

The syntax of the ternary operator is: condition ? expression_if_true : expression_if_false;

C++
#include <iostream>
using namespace std;

int main() {
    int a = 10, b = 20;
    int max = (a > b) ? a : b;
    cout << "Maximum value is " << max << endl;
    return 0;
}

2. Using Ternary Operator in Output

The ternary operator can be used directly inside cout or expressions.

C++
#include <iostream>
using namespace std;

int main() {
    int age = 18;
    cout << ((age >= 18) ? "Eligible to vote" : "Not eligible to vote") << endl;
    return 0;
}

3. Nested Ternary Operator

Ternary operators can be nested to handle multiple conditions, but readability may decrease.

C++
#include <iostream>
using namespace std;

int main() {
    int marks = 75;
    string grade = (marks >= 90) ? "A" : (marks >= 75) ? "B" : "C";
    cout << "Grade: " << grade << endl;
    return 0;
}

4. Combined Program

This program demonstrates multiple ternary operations together.

C++
#include <iostream>
using namespace std;

int main() {
    int a = 10, b = 20, c = 15;

    int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);
    cout << "Maximum value among a, b, c = " << max << endl;

    int num = -5;
    cout << ((num >= 0) ? "Positive" : "Negative") << endl;

    int age = 17;
    cout << ((age >= 18) ? "Eligible to vote" : "Not eligible") << endl;

    return 0;
}

Conclusion

The ternary operator ?: in C++ allows writing concise conditional expressions. Use it for simple if-else logic, and avoid over-nesting to maintain code readability.