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.