What is checked in the following condition:
while(cin >> x)
to have a while loop continue going? What's the boolean value of an expression assignment in the code above?
What is checked in the following condition:
while(cin >> x)
to have a while loop continue going? What's the boolean value of an expression assignment in the code above?
The expression result of cin >> x
is a reference to the cin
stream, a std::istream
.
A std::istream
effectively converts to boolean when used as an if
or while
condition expression.
The result is equivalent to writing
!cin.fail()
.
In C++03 the conversion was technically an operator void*()
.
That, however, was not so nice with respect to overload resolution and some other issues.
So in C++11 it's an explicit operator bool()
. The keyword explicit
could only be used on constructors in C++03, but in C++11 it can also be applied to conversion operators. It prevents the usual inadvertent implicit conversions, but as a special case it is effectively ignored for conversion to boolean of an if
or while
condition expression.
cin
is an instance of istream
template class. operator >>
acts on this istream instance to load input into data and returns a reference to this istream
. Then in while
condition it is tested by a call to cin::operator void*() const
(explicit operator bool() const
in C++11) which invokes fail()
function to test if operation succeeded. This is why you can use this operation in while condition
while ( cin >> x)
{
//...
The return type of operator >>
for std::istream
is std::istream
again. It returns the left-hand argument (cin
in your case). And std::istream
has an operator bool()
which enables using a stream in a conditional expression. These two things together enable testing of a stream the same way we test many other C++ objects for validity, such as pointers.