I found a piece of C-ish C++ code and asked myself the (slightly academic) question, what implicit type conversions happen here to arrive at the bool that if requires?
int val;
if( (std::cin >> val) == 0 )
...
I got this far:
std::cin >> val returns (a ref to) cin, thus istream&
== receives cin and 0 as operands, i.e. istream and int
I don't think there is a bool operator==(istream&, int) available (nor the respective member function in istream), so is there a conversion involved?
Just to be clear, the programmers intention was to check if the input was a success, i.e. should have written if(!(std::cin >> val)).
I don't think there is a
bool operator==(istream&, int)available [...] so is there a conversion involved?
Indeed. There is a conversion operator to bool that returns true if no errors occurred, and false otherwise.
Per paragraph 27.5.5.4/1 of the C++11 Standard:
explicit operator bool() const;1 Returns:
!fail().
So the expression (cin >> val) gives you back a (reference to) cin, which is the left operand of ==. The right operand is 0.
Now cin can be converted to bool, and that allows the comparison with 0. In other words, your if statement is equivalent to:
if (!(std::cin >> val))
{
// ...
}
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