10

I am curious if std::cout has a return value, because when I do this:

cout << cout << "";

some hexa code is printed. What's the meaning of this printed value?

Drise
  • 4,164
  • 5
  • 38
  • 64
user1448323
  • 151
  • 1
  • 2
  • 7
  • 1
    Though the question itself isn't (quite) an exact duplicate, most of the answers to a [previous question](http://stackoverflow.com/q/7489069/179910) apply here as well. – Jerry Coffin Jun 11 '12 at 20:40

3 Answers3

19

Because the operands of cout << cout are user-defined types, the expression is effectively a function call. The compiler must find the best operator<< that matches the operands, which in this case are both of type std::ostream.

There are many candidate operator overloads from which to choose, but I'll just describe the one that ends up getting selected, following the usual overload resolution process.

std::ostream has a conversion operator that allows conversion to void*. This is used to enable testing the state of the stream as a boolean condition (i.e., it allows if (cout) to work).

The right-hand operand expression cout is implicitly converted to void const* using this conversion operator, then the operator<< overload that takes an ostream& and a void const* is called to write this pointer value.

Note that the actual value resulting from the ostream to void* conversion is unspecified. The specification only mandates that if the stream is in a bad state, a null pointer is returned, otherwise a non-null pointer is returned.


The operator<< overloads for stream insertion do have a return value: they return the stream that was provided as an operand. This is what allows chaining of insertion operations (and for input streams, extraction operations using >>).

James McNellis
  • 338,529
  • 73
  • 897
  • 968
15

cout does not have a return value. cout is an object of type ostream. operator << has a return value, it returns a reference to cout.

See http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/ for reference.

The only signature that matches is:

ostream& operator<< (ostream& ( *pf )(ostream&));

so it returns the pointer to the operator<< member.

the one in James' answer. :)

Luchian Grigore
  • 245,575
  • 61
  • 446
  • 609
  • 1
    I can't see any way that this code semantically evaluates to "print the address of an `operator< – cdhowie Jun 11 '12 at 20:39
1

I believe that would be the address of the ostream object that "" got printed to

Kyle Preiksa
  • 506
  • 2
  • 5
  • 23