I thought that:
if (true)
{execute this statement}
So how does if (std::cin >> X)
execute as true when there is nothing
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.
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)
.
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.
The answer depends on the version of the standard C++ library:
if
relied on converting the stream to void*
using operator void*
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.