1

I read this line and I don't understand what it does:

if(cout<<X) //What does this mean? 
{
...
}
Magnus Hoff
  • 20,855
  • 9
  • 60
  • 81
Sana Joseph
  • 1,918
  • 7
  • 36
  • 57

4 Answers4

6

It writes X to cout and checks to see if the stream is still in a good state. It is the same as

cout << X;
if (cout) {
   // ....
}

This works because the result of stream << value is a reference to the stream. This is also why you can do things like

stream << x << y << z;

since it is the same as

((stream << x) << y) << z;
Vaughn Cato
  • 61,903
  • 5
  • 80
  • 122
2

In C++, the iostream insertion and extraction operators << and >> return the object on which they were invoked (i.e. their left-hand argument). So if(cout<<X) first inserts X into the cout stream, then uses that stream as a conditional. And iostreams, when tested as booleans, report their status: true if OK, false if in an error state.

So the whole thing means "Print X and then run the following code if cout has no error."

John Zwinck
  • 223,042
  • 33
  • 293
  • 407
1

Any expression that contains a stream (such as the ostream of cout, and since operator<<(ostream &os, ...) returns an ostream, the cout << X counts here) will be converted to a boolean expression that is true if the output (or input, in relevant cases) was a "success" (in other words, didn't fail in some way). If cout is redirected to a file on a disk that becomes full, for example, it would fail.

Mats Petersson
  • 123,518
  • 13
  • 127
  • 216
1

The IO library redefines the bitwise >>and << operators to do input and output and return itself. So that if(cout<<X) means that output X to cout and then return cout for condition check: if(cout), which checks if cout is in an error state.

Yu Hao
  • 115,525
  • 42
  • 225
  • 281