Reputation: 779
General prototype: exp1?exp2:exp3
Ternary operator has a return type of exp2. It is necessary for exp3 to have same return type as exp2 or at least have an implicit conversion. Otherwise it will throw error
In the below program, I am getting an error in CodeBlocks as expected because of exp3 being int and exp2 being char*. Bjut when I am replacing 1 with 0, it is printing 0..
0 is also an int value.I am not able to understand.
#include <iostream>
using namespace std;
int main()
{
int test = 0;
cout << test ? "A String" : 1;
return 0;
}
Upvotes: 2
Views: 164
Reputation: 153840
The ternary operator has rather low precedence. The only operator with lower precedence is the comma operator. Thus, your expression is interpreted as
(std::cout << test) ? "A String": 1;
This is probably not quite what you want. However, your question is actually about the difference between two expressions:
the expression
expr? "A String": 1
is not working because there is no common type between a string literal, i.e., the type char const(&)[9]
, and an integer literal, i.e., the type int
.
the expression
expr? "A String": 0
is working because 0
can be considered to be a pointer constant and a string literal would happily decay to a char const*
.
It is worth noting, as Chris Culter pointed out, that using a null pointer with the output operator is undefined behavior according to 27.7.3.6.4 [ostream.inserter.character] paragraph 3:
template<class traits> basic_ostream<char,traits>& operator<<(basic_ostream<char,traits>& out, const char* s);
[...]
Requires: s shall not be a null pointer.
Upvotes: 8
Reputation: 6251
The stream operator has higher precedence so it will always output test. Try:
cout << (test ? "A String" : 1);
Upvotes: 2