1

I was writing code using ternary operator instead of if/else to save some time in Competitive Programming. But I was stuck in one case and here is the code

std::cout<< a%2? "string1" : "string2";

OUTPUT on my system: 0 or 1 as per 'a'

Excepted: string1 or string2

I think here ternary operator is returning "const char *" after evaluation, but I'm not getting expected results. So here are my doubts about it.

  1. Why const char * ram = "ram"; std::cout<<ram; works fine but above code don't, to me both seems to have const char * as input to cout, so what is difference between them?
  2. Any workaround to print strings as intended above using ternary operator?
rkscodes
  • 85
  • 7

1 Answers1

4

operator<< has higher precedence than ternary conditional operator, so std::cout<< a%2? "string1" : "string2"; has the same effect as (std::cout<< a%2) ? "string1" : "string2";. As the result a%2 is printed out instead. (std::cout<< a%2 returns std::cout, which could convert to bool, regardless of the result is true or false, "string1" or "string2" don't have any effect here.)

You should add parentheses like

std::cout<< (a%2? "string1" : "string2");
songyuanyao
  • 169,198
  • 16
  • 310
  • 405