0

What does this condition mean??👉if (!(cout << "geeks"))    

int main() {     if (!(cout << "geeks"))            cout <<" geeks ";         else            cout << "forgeeks ";            return 0; }

24th Sep 2018, 2:17 AM
looper
looper - avatar
6 ответов
+ 2
The result stream << operator is the stream itself. It means that (cout << "geeks") returns cout, casted to it's base. The stream could be casted to bool. In that case it returns it's state: true if stream ok, false if stream failed or closed. So !(cout << "geeks") is true when operation failed.
24th Sep 2018, 4:04 AM
Sergey Ushakov
Sergey Ushakov - avatar
+ 1
Interesting...if someone wants to take this, try this line: printf("%x", (cout<<"geeks")); Note the error: error: use of deleted function : basic_ostream(const basic_ostream&) = delete I think...read these: https://stackoverflow.com/questions/20257836/c-ostream-implicitly-deleted-with-template https://abseil.io/tips/143 "Deleted functions" And note this works: printf(" [%x]", &(cout<<"geeks"));
24th Sep 2018, 3:09 AM
Kirk Schafer
Kirk Schafer - avatar
+ 1
Additional info for what it may actually be doing: https://godbolt.org/z/ahyaNx I suspect the important assembly output lines are 12 and 18, if there's a way to interpret that or override "operator !"
24th Sep 2018, 3:38 AM
Kirk Schafer
Kirk Schafer - avatar
+ 1
Console window could be closed, parent program could close your cout from its side, your cout could be redirected to a file and there is no more space on the storage... There is multiple reasons why cout could be invalid. It is a your decision to check status of cout or not.
24th Sep 2018, 6:55 AM
Sergey Ushakov
Sergey Ushakov - avatar
+ 1
Based on the thread's movement so far, some corroborating comments on usage and how << and >> return their left-side argument: https://stackoverflow.com/questions/16964066/if-condition-checking-for-cout Additional on "why fail?", this thread is full of code having trouble in Visual Studio with I/O handles being invalid (just for the comments, they explain how I/O has to be set to NUL to reset the error state, then redirected again): https://stackoverflow.com/questions/311955/redirecting-cout-to-a-console-in-windows/424236#424236
24th Sep 2018, 4:07 PM
Kirk Schafer
Kirk Schafer - avatar
0
Interesting, I have never seen this in use. Why would a cout stream fail anyway? Shouldn't we test all couts every time then? 😅 I don't understand why this should be useful in practice Sergey Ushakov
24th Sep 2018, 5:57 AM
Matthias
Matthias - avatar