C/C++ Ternary Operator

CC++Server Side ProgrammingProgramming

C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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 << "";
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
Updated on 26-Sep-2019 13:36:49