Husam Chekfa
Husam Chekfa

Reputation: 77

What does !(cout << ....) mean

I just came across a code snippet in C++ here: https://www.geeksforgeeks.org/c-cpp-tricky-programs/

One of the snippets is basically:

if (!(cout << "A")) {
    cout <<" B ";
}
else {
    cout << "C ";
}

The output is: "AC"

What exactly does the argument in the if clause mean ? And how would you word it in regular English ?

My guess is it means: if "A" is not printable, then print "B", but I am not sure.

Also, is this syntax used often ? I think this is the first time I see cout in an argument, though I have seen getc or getch in the argument clause before.

Thank you in advance :D

Upvotes: 0

Views: 970

Answers (1)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122585

First, std::cout::operator<< returns a reference to the stream.

Next, std::ostream has an operator bool (inherited from std::basic_ios):

Returns true if the stream has no errors and is ready for I/O operations. Specifically, returns !fail().

Hence, what happens is that cout << "A" prints "A", then returns a reference to std::cout, this is implciticly converted to bool. As std::cout is not in an error state it is true and !true lets the if enter the else branch.


Note that the comment that comes with the code is misleading:

// CPP program to verifies the condition inside if block
// It just verifies the condition inside if block,
// i.e., cout << "geeks" which returns a non-zero value,
// !(non-zero value) is false, hence it executes else

std::cout is certainly not 0, but thats not the reason the condition evaluates to !true! The reason is that std::cout::operator bool is called to perform the implicit conversion to bool.


Last but not least, the example is completely silly. It basically says: When the stream is not in a failure state then print something, when it is in a failure state then try to print something anyhow. That does not make much sense. On the other hand, using the implicit conversion to bool is common when reading input from the user:

if (std::cin >> x) {
    ... use x ...
} else {
    std::cout << "reading input failed";
}

Upvotes: 4

Related Questions