Reputation: 111
I thought that:
if (true)
{execute this statement}
So how does if (std::cin >> X)
execute as true when there is nothing "true" about it? I could understand if it was if ( x <= y)
or if ( y [operator] x )
, but what kind of logic is "istream = true?".
Upvotes: 8
Views: 1943
Reputation: 5218
What is inside if
condition will be evaluated to bool
.
if(cin >> X)
means that if condition is true
, something was read to X
; if condition is false
, something else happened (e.g. stream ended) and X
is not changed.
E.g. to read until the end of stream, you can use while(cin >> X)
.
Upvotes: 3
Reputation: 69854
if(x)
is equivalent to if(bool(x))
in this case bool(x)
calls std::istream::operator bool(x)
this will return:
true if none of
failbit
orbadbit
is set.false otherwise.
Upvotes: 5
Reputation: 726479
The answer depends on the version of the standard C++ library:
if
relied on converting the stream to void*
using operator void*
operator bool
of std::istream
Note that std::cin >> X
is not only a statement, but also an expression. It returns std::cin
. This behavior is required for "chained" input, e.g. std::cin >> X >> Y >> Z
. The same behavior comes in handy when you place input inside an if
: the resultant stream gets passed to operator bool
or operator void*
, so a boolean value gets fed to the conditional.
Upvotes: 13
Reputation: 49976
std::cin
is of type std::basic_istream
which inherits from std::basic_ios, which has an operator : std::basic_ios::operator bool which is called when used in if statement.
Upvotes: 7