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?".
cin. fail() - This function returns true when an input failure occurs. In this case it would be an input that is not an integer. If the cin fails then the input buffer is kept in an error state.
Lets take an example to understand why if condition always evaluates to true: The statement if(variable) will evaluate to false only if variable is either 0 or NULL. Since there are other strings in your if statement, ORing them always evaluates to 1. Hence its always true.
If either (or both) of the two values it checks are TRUE then it returns TRUE. For example, (1) OR (0) evaluates to 1. (0) OR (0) evaluates to 0. The OR is written as || in C++.
Thus, cin means "character input". The C++ cin object belongs to the istream class. It accepts input from a standard input device, such as a keyboard, and is linked to stdin, the regular C input source. For reading inputs, the extraction operator(>>) is combined with the object cin.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With