- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C/C++ Ternary Operator
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.
#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