Search code examples
c++booleanimplicit-conversionistream

What implicit conversions happen with istream?


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&
  • Therefore == 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)).


Solution

  • 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))
    {
        // ...
    }