Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 862
chaosfirebit Avatar asked Apr 14 '16 14:04

chaosfirebit


People also ask

Does CIN return true?

cin. fail() - This function returns true when an input failure occurs. In this case it would be an input that is not an integer. If the cin fails then the input buffer is kept in an error state.

What must the if condition always evaluate to?

Lets take an example to understand why if condition always evaluates to true: The statement if(variable) will evaluate to false only if variable is either 0 or NULL. Since there are other strings in your if statement, ORing them always evaluates to 1. Hence its always true.

How do you say or in an if statement in C++?

If either (or both) of the two values it checks are TRUE then it returns TRUE. For example, (1) OR (0) evaluates to 1. (0) OR (0) evaluates to 0. The OR is written as || in C++.

How does Cin work in C?

Thus, cin means "character input". The C++ cin object belongs to the istream class. It accepts input from a standard input device, such as a keyboard, and is linked to stdin, the regular C input source. For reading inputs, the extraction operator(>>) is combined with the object cin.


2 Answers

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.

like image 154
Sergey Kalinichenko Avatar answered Sep 19 '22 13:09

Sergey Kalinichenko


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.

like image 32
marcinj Avatar answered Sep 19 '22 13:09

marcinj