2

I have a flimsy understanding of how/why istream can be used in conditionals. I have read this question:(Why istream object can be used as a bool expression?).

I don't understand why this compiles without error…

while (cin >> n) {
    // things and stuff
}

…while this fails to compile (message error: invalid operands to binary expression ('int' and '__istream_type' (aka 'basic_istream<char, std::char_traits<char> >')))

while (true == (cin >> n)) {
    // things and stuff
}
Community
  • 1
  • 1
griotspeak
  • 12,532
  • 12
  • 38
  • 54

2 Answers2

2

Because the implicit conversion operator of cin is

operator void*() const { ... }

and it can evaluate to zero, so you can check it against zero

while (cin >> x) {}

Conversion operator for bool declared as explicit so your expression will not invoke it:

explicit operator bool(){ ... }

So, you need an explicit cast:

if (true == static_cast<bool>(cin >> a))
{
}
Pete Becker
  • 69,019
  • 6
  • 64
  • 147
masoud
  • 51,434
  • 14
  • 119
  • 190
  • There's also an `operator bool()`. – 0x499602D2 Nov 02 '13 at 23:13
  • 1
    @0x499602D2, Also might be a bit much. It was *changed* to `explicit operator bool()` in C++11. – chris Nov 02 '13 at 23:14
  • Interesting. I thought that I might have to cast but didn't understand why. Thank you. (can't accept answer yet.) – griotspeak Nov 02 '13 at 23:17
  • You say that 'it's just useful for testing against `0`' But that expression evaluates to true when cin reads a 0 as well. Does that (the 0 that you mentioned) mean that `cin` returned `NULL|nullptr` from the implicit cast? – griotspeak Nov 02 '13 at 23:20
  • I edited that part a little. For more info read [this](http://stackoverflow.com/a/19385215/952747). That operator returns `!fail()`. – masoud Nov 02 '13 at 23:25
0

cin >> n returns an istream&. Because the result is used in a comparison, the compiler searches for an operator==(bool, istream), which it cannot find. Therefore, you get an error message.

Olaf Dietsche
  • 66,104
  • 6
  • 91
  • 177