0
What does this condition mean??👉if (!(cout << "geeks"))
int main() { if (!(cout << "geeks")) cout <<" geeks "; else cout << "forgeeks "; return 0; }
6 Answers
+ 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.
+ 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"));
+ 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 !"
+ 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.
+ 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
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