C/C++ Ternary Operator

CC++Server Side ProgrammingProgramming

Syntax of ternary operator is −

(expression-1) ? expression-2 : expression-3

This operator returns one of two values depending on the result of an expression. If "expression-1" is evaluated to Boolean true, then expression-2 is evaluated and its value is returned as a final result otherwise expression-3 is evaluated and its value is returned as a final result.

Example

Let us write a program to find maximum of two numbers using ternary operator.

 Live Demo

#include <iostream>
using namespace std;
int main() {
   int a = 10;
   int b = 20;
   int max = a > b ? a : b;
   cout << "Maximum value = " << max << "\n";
   return 0;
}

If we compare syntax of ternary operator with above example, then −

  • expression-1 is (a > b)
  • expression-2 is a
  • expression-3 is b

First, expression a > b is evaluated, which evaluates to Boolean false as value of variable 'a' is smaller than value of variable 'b'. Hence value of variable 'b' i.e. '20' is returned which becomes final result and gets assigned to variable 'max'.

Output

When you compile and execute above code it will generate following output −

Maximum value = 20
raja
Published on 26-Sep-2019 13:35:44
Advertisements