Some Interesting Observations about C/C++ Ternary Operator


We know that ternary operator is implemented instead of if..else clause. It is denoted by ?: . '?' symbol is equivalent to if part and ':' is equivalent to else part. The following 3 programs explain some interesting observation in case of ternary operator.

The following program is able to compile without any error. Ternary expression’s return type is expected to be float (as that of exp2) and exp3 (i.e. literal zero - int type) is able to implicitly convert to float.

#include <iostream>
using namespace std;
int main(){
   int test1 = 0;
   float fvalue = 3.111f;
   cout<< (test1 ? fvalue : 0) << endl;
   return 0;
}

The following program will not be able to compile, reason is that the compiler is not able to locate or find return type of ternary expression or implicit conversion is unavailable between exp2 (char array) and exp3 (int).

#include <iostream>
using namespace std;
int main(){
   int test1 = 0;
   cout<< test1 ? "A String" : 0 << endl;
   return 0;
}

The following program may be able to compile, or but fails at runtime. Ternary expression’s return type is limited or bounded to type (char *), yet the expression returns int, so the program fails. In literal, the program tries to print string at 0th address at execution time or runtime.

#include <iostream>
using namespace std;
int main(){
   int test1 = 0;
   cout << (test1 ? "A String" : 0) << endl;
   return 0;
}

We can observe that exp2 is treated as output type and exp3 will be able to convert into exp2 at execution time or runtime. If the conversion is treated as implicit then the compiler inserts stubs for conversion. If the conversion is treated as explicit the compiler throws an error. If any compiler is able to miss to catch such error, the program may fail at execution time or runtime.

Updated on: 29-Jan-2020

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements