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

后端 未结 4 1363
一生所求
一生所求 2021-01-12 12:18

I thought that:

if (true) 
{execute this statement}

So how does if (std::cin >> X) execute as true when there is nothing

相关标签:
4条回答
  • 2021-01-12 13:04

    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.

    0 讨论(0)
  • 2021-01-12 13:14

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

    0 讨论(0)
  • 2021-01-12 13:15

    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.

    0 讨论(0)
  • 2021-01-12 13:22

    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.

    0 讨论(0)
提交回复
热议问题