Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

How does that funky while (cin >> foo) syntax work?

cin foo funky syntax
0
10 Posted

How does that funky while (cin >> foo) syntax work?

0
10

See the previous FAQ for an example of the “funky while (cin >> foo) syntax.” The expression (cin >> foo) calls the appropriate operator>> (for example, it calls the operator>> that takes an istream on the left and, if foo is of type int, an int& on the right). The istream operator>> functions return their left argument by convention, which in this case means it will return cin. Next the compiler notices that the returned istream is in a boolean context, so it calls the “cast” operator istream::operator bool(). I.e., in this case, it calls cin.operator bool(), just as if you had casted it explicitly such as (bool)cin or bool(cin). (Note: if your compiler doesn’t yet support the bool type, istream::operator void*() will be called instead.) The operator bool() cast operator returns true if the stream is in a good state, or false if it’s in a failed state (in the void* case, the return values will be some non-NULL pointer or the NULL pointer, respectively). For example, if you read one to

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.