
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
Advertisements