I read this line and I don't understand what it does:
if(cout<<X) //What does this mean?
{
...
}
I read this line and I don't understand what it does:
if(cout<<X) //What does this mean?
{
...
}
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;
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."
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.
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.