2

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

if(cout<<X) //What does this mean? 
{
...
}
Magnus Hoff
  • 21,529
  • 9
  • 63
  • 82
Sana Joseph
  • 1,948
  • 7
  • 37
  • 58

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
  • 63,448
  • 5
  • 82
  • 132
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
  • 239,568
  • 38
  • 324
  • 436
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
  • 126,704
  • 14
  • 140
  • 227
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
  • 119,891
  • 44
  • 235
  • 294