Syntax of Ternary Operator ( ? : )

The syntax of the ternary (or conditional) operator is:

expression ? statement_1 : statement_2;

As the name suggests, the ternary operator works on three operands where

  • expression: Condition to be evaluated.
  • statement_1: Statement that will be executed if the expression evaluates to true.
  • statement_2: Code to be executed if the expression evaluates to false.

// image

The above statement of the ternary operator is equivalent to the if-else statement given below:

if ( condition ) {
statement1;
}
else {
statement2;
}

C++ Ternary or Conditional Operator

In C++, the ternary or conditional operator ( ? : ) is the shortest form of writing conditional statements. It can be used as an inline conditional statement in place of if-else to execute some conditional code.

Similar Reads

Syntax of Ternary Operator ( ? : )

The syntax of the ternary (or conditional) operator is:...

Example of Ternary Operator in C++

C++ // C++ program to illustrate the use of ternary operator #include using namespace std;    int main() {        // creating a variable     int num, test = 40;        // assigning the value of num based on the value of test     // variable     num = test < 10 ? 10 : test + 10;        printf("Num - Test = %d", num - test);        return 0; }...

C++ Nested Ternary Operator

...