Ternary operator ?: vs if…else in C/C++

C++Server Side ProgrammingProgramming

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
raja
Published on 04-Apr-2019 17:07:47
Advertisements