Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operator used in cout statement

By trying, I came to know that it is necessary to put parentheses around a conditional operator in a cout statement. Here a small example:

#include <iostream>

int main() {
  int a = 5;
  float b = (a!=0) ? 42.0f : -42.0f;
  // works fine
  std::cout << b << std::endl;
  // works also fine
  std::cout << ( (a != 0) ? 42.0f : -42.0f ) << std::endl;
  // does not work fine
  std::cout << (a != 0) ? 42.0f : -42.0f;

  return 0;
}

The output is:

42
42
1

Why are these parentheses necessary? The resulting type of the conditional operator is known in both cases, isn't it?

like image 412
m47h Avatar asked Mar 08 '12 14:03

m47h


People also ask

How do you use conditional operator in cout?

Just a note, cout<< returns cout , not anything about valid state. failbit/badbit will be set, but (std::cout << (a != 0)) always returns a reference to std::cout . -42.0f should never be returned, as that reference should always boolean evaluate to true.

What is conditional operator in C++?

The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows: The first operand is implicitly converted to bool . It is evaluated and all side effects are completed before continuing.

Which operators are used in conditional statement?

There are three conditional operators: && the logical AND operator. || the logical OR operator. ?: the ternary operator.

Can we use ternary operator in cout?

Here with in cout chain we use the ternary operator as – First operand is check condition if the c=='Y'. Second operand – String literal “YES“, Third Operand – String Literal “NO“. This will print YES as first condition is true. The whole expression should be in a round brace pair as it is inside the cout chain.


1 Answers

The ?: operator has lower precedence than the << operator i.e., the compiler interprets your last statement as:

(std::cout << (a != 0)) ? 42.0f : -42.0f;

Which will first stream the boolean value of (a!=0) to cout. Then the result of that expression (i.e., a reference to cout) will be cast to an appropriate type for use in the ?: operator (namely void*: see cplusplus.com), and depending on whether that value is true (i.e., whether cout has no error flags set), it will grab either the value 42 or the value -42. Finally, it will throw that value away (since nothing uses it).

like image 56
Edward Loper Avatar answered Oct 20 '22 10:10

Edward Loper