8

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

Danny Herbert
  • 2,002
  • 1
  • 18
  • 26
chaosfirebit
  • 111
  • 2
  • 8
  • 1
    if "accepts" a bool. therefore anything inside the ( ) will be casted to bool, through operator bool(); also, see http://stackoverflow.com/questions/6791520/if-cin-x-why-can-you-use-that-condition – Exceptyon Apr 14 '16 at 14:59
  • 3
    A stream is "true-ish" if the last operation was successful. – molbdnilo Apr 14 '16 at 15:00
  • 4
    The first question you need to ask yourself is what is the value of the expression `(std::cin >> X)`. – Kerrek SB Apr 14 '16 at 15:01
  • @Exceptyon so that means any iostream evaluates to true? or only cin? sorry for the noob question – chaosfirebit Apr 14 '16 at 15:01
  • @chaosfirebit should return true if the read was successful. therefore if there was something left to read and conversion could be performed. int x; cin>>x; will return false on input "test" – Exceptyon Apr 14 '16 at 15:02
  • @Exceptyon Thanks for the clarification – chaosfirebit Apr 14 '16 at 15:04

4 Answers4

12

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
7

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.

marcinj
  • 48,511
  • 9
  • 79
  • 100
5

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.

Community
  • 1
  • 1
Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
3

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).

George Sovetov
  • 4,942
  • 5
  • 36
  • 57