What would happen if I used a cout statement as the condition for an if statement?

So, my programming instructor asked me to try putting a cout-statement as the condition for an if-statement and see what happens. I tried it (just made a random code) and didn't notice anythimg special. Here's the code.

#include<iostream>
using namespace std;
int main()
{
    int x=1;
    int y=2022;
    if(cout<<"Covid")
    {
        cout << "\n Us \n";
        x=y;
        cout << x;
    }
}

The output is simply

Covid
Us
2022

What I don't understand is why this would be used. From my amateur understanding, even if I used an else-statement or any amount of else-if statements, they wouldn't run, since the condition for the if-statement is self-fulfilling. I could the simply write the whole code directly without using an if-statement. What then, could be the purpose of using an if-statement? Any general use?


Solution 1:

Prior to C++11, when you write if(cout << "Covid"), there is an implicit conversion to void*. This value is unspecified by the C++ standard, other than if the stream is in an error state, then nullptr is returned.

From C++11, the implicit conversion is to bool. false denotes the stream is in an error state, true otherwise.

Note that you must have imbued a very funky iostream-derived object indeed for the output to be "Pakistan" given your input!