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" in it? I could understand if it was if ( x <= y) or if ( y [operator] x ) , but what is the logic "istream = true?".

+5
source share
4 answers

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

  • Prior to C ++ 11, the conversion inside the if based on converting the stream to void* using operator void*
  • Starting with C ++ 11, conversion depends on operator bool std::istream

Note that std::cin >> X is not only an operator, but also an expression. It returns std::cin . This behavior is required for chained input, for example. std::cin >> X >> Y >> Z The same behavior is useful when placing the input inside the if : the resulting stream is passed to the operator bool or operator void* , so the logical value is passed to the conditional expression.

+9
source

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 an if statement.

+5
source

if(x) 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 .

false otherwise.

+3
source

What is inside the if condition will be evaluated before bool .

if(cin >> X) means that if the condition is true , something was read on X ; if the condition is false , something else happened (for example, the thread ended) and X does not change.

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

+3
source

Source: https://habr.com/ru/post/1247140/


All Articles