chaosfirebit
chaosfirebit

Reputation: 111

How does cin evaluate to true when inside an if statement?

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?".

Upvotes: 8

Views: 1943

Answers (4)

George Sovetov
George Sovetov

Reputation: 5218

What is inside if condition will be evaluated to bool.

if(cin >> X) means that if condition is true, something was read to X; if condition is false, something else happened (e.g. stream ended) and X is not changed.

E.g. to read until the end of stream, you can use while(cin >> X).

Upvotes: 3

Richard Hodges
Richard Hodges

Reputation: 69854

if(x) is equivalent to if(bool(x))

in this case bool(x) calls std::istream::operator bool(x)

this will return:

true if none of failbit or badbit is set.

false otherwise.

Upvotes: 5

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

The answer depends on the version of the standard C++ library:

  • Prior to C++11 the conversion inside if relied on converting the stream to void* using operator void*
  • Starting with C++11 the conversion relies on 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.

Upvotes: 13

marcinj
marcinj

Reputation: 49976

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.

Upvotes: 7

Related Questions