2

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;
   }
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Tanu Saxena
  • 779
  • 6
  • 15

2 Answers2

8

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:

  1. 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.

  2. 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.

Community
  • 1
  • 1
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • Overly nitpicky, but the only pointer literal is `nullptr`, 0 is an integer literal that is also a null pointer constant. – user657267 Nov 06 '14 at 06:25
  • 1
    @user657267: yes, I think you are right. I edited the response correspondingly. – Dietmar Kühl Nov 06 '14 at 06:30
  • Somewhat off-topic, but it's worth mentioning that one shouldn't actually pass a null pointer to `operator<<(ostream, char const*)`, as the result is undefined behavior (citation in [this answer](http://stackoverflow.com/questions/7019454/why-does-stdcout-output-disappear-completely-after-null-is-sent-to-it)). For example, libc++ bravely calls `strlen` on the pointer and crashes. – Chris Culter Nov 06 '14 at 06:34
  • @ChrisCulter: I have updated the response accordingly. – Dietmar Kühl Nov 06 '14 at 06:40
2

The stream operator has higher precedence so it will always output test. Try:

cout << (test ? "A String" : 1);
ryanpattison
  • 6,151
  • 1
  • 21
  • 28