How does cin evaluate to true when inside an if statement?
The answer depends on the version of the standard C++ library:
- Prior to C++11 the conversion inside
if
relied on converting the stream tovoid*
usingoperator void*
- Starting with C++11 the conversion relies on
operator bool
ofstd::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.
What is the difference between if (cin >> x) and if (!(cin >> x).fail())?
Here the expression cin >> x
performs an input operation that might update x
, and as its expression result returns a reference to the stream, i.e. to cin
. So cin
is being used directly as a condition. That invokes a conversion to boolean, which is defined such that it on its own is equivalent to !cin.fail()
(i.e., the expression cin >> x
as condition is equivalent to writing !(cin >> x).fail()
or, as a comma expression, (cin >> x, !cin.fail())
.
about while (!(cin>>x))
You use
cin >> number;
And then
while (!(cin>>x))
Both of which read a number.
Related Topics
Difference Between Conversion Specifiers %I and %D in Formatted Io Functions (*Printf/*Scanf)
Why Is a Pure Virtual Function Initialized by 0
Will Using Goto Leak Variables
How Is Std::Function Implemented
C++ Function Template Partial Specialization
C++: Print Out Enum Value as Text
Order of Calling Constructors/Destructors in Inheritance
Is Passing Pointer Argument, Pass by Value in C++
Constants and Compiler Optimization in C++
Catch Exception by Pointer in C++
How to Check Whether Operator== Exists
What Happens in a Double Delete
What Is the Purpose of Std::Launder
Why Are C++ Inline Functions in the Header
How to Construct a Std::String With Embedded Values, I.E. "String Interpolation"
Why Do C++11-Deleted Functions Participate in Overload Resolution