- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Ternary operator ?: vs if…else in C/C++
We know that the ternary operator is the conditional operator. Using this operator, we can check some condition and do some task according to that condition. Without using the ternary operator, we can also use the if-else conditions to do the same.
The effect of ternary operator and if-else condition are same in most of the cases. Sometime in some situation we cannot use the if-else condition. We have to use the ternary operator in that situation. One of this situation is assigning some value into some constant variable. We cannot assign values into constant variable using if-else condition. But using ternary operator we can assign value into some constant variable
Example Code
#include<iostream> using namespace std; main() { int a = 10, b = 20; const int x; if(a < b) { x = a; } else { x = b; } cout << x; }
Output
This program will not be compiled because we are trying to use the constant variable in different statement, that is not valid.
By using ternary operator, it will work.
Example Code
#include<iostream> using namespace std; main() { int a = 10, b = 20; const int x = (a < b) ? a : b; cout << x; }
Output
10
- Related Articles
- If elseif else or ternary operator to compare numbers PHP?
- C/C++ Ternary Operator
- Ternary Operator in C#
- Conditional ternary operator ( ?: ) in C++
- How can we use Python Ternary Operator Without else?
- How do I use the ternary operator ( ? : ) in PHP as a shorthand for “if / else”?
- What is ternary operator in C#?
- What is a Ternary operator/conditional operator in C#?
- Some Interesting Observations about C/C++ Ternary Operator
- What is ternary operator (? X : Y) in C++?
- Ternary Operator in Python?
- Ternary Operator in Java
- Copy constructor vs assignment operator in C++
- Program to find the Largest Number using Ternary Operator in C++
- Changing ternary operator into non-ternary - JavaScript?

Advertisements