Why in conditional operator(?:
), second and third operands must have the same type?
My code like this:
#include
You should try to decompose what's happening to understand:
cout << ( a>b ? "a is greater\n" : b );
This translates to :
operator<<(cout, ( a>b ? "a is greater\n" : b ));
At that stage the compiler must choose one of the following overloads:
ostream& operator<<(ostream&, int);
ostream& operator<<(ostream&, const char*);
But it can't because the type of result of the ternary operator is not known yet (only at runtime).
To make things clearer think like this:
auto c = a>b ? "test" : 0;
What would be the type of c
? It can't be decided at compile time. C++ is a statically typed language. All types must be known at compile time.
You are thinking of a ? b : c
in the following way:
if (a)
b;
else
c;
While it is actually this:
if (a)
return b;
else
return c;