0

Can somebody explain to me why this program sends an address to std::cout?

#include<string>
#include<iostream>
#include<fstream>


std::ostream& stuff(std::ostream& o, std::string s)
{
    o << s << std::endl;
    return o;
}

int main(){

    std::cout << stuff(std::cout, "word") << std::endl;

}

It is caused by the std::endl in main().. but why??

output:

word
0x804a064
lo tolmencre
  • 3,804
  • 3
  • 30
  • 60

1 Answers1

3

Your function stuff returns the std::ostream that was passed into it.

That means your code:

std::cout << stuff(std::cout, "word") << std::endl;

Will actually call:

std::cout << (std::cout) << std::endl;
             ^^^^^^^^^^^ this is the result of calling "stuff"

You are outputting the address of your std::cout object.

Your program is functionally equivalent to:

std::cout << "word" << std::endl;
std::cout << std::cout << std::endl;
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • why does the ouput change when removing endl in main()? The address will disappear then. – lo tolmencre Jul 04 '15 at 05:00
  • @lotolmencre that's not described anywhere in your question. If you have a new question, ask a new question. Good luck! – Drew Dormann Jul 04 '15 at 05:01
  • Huh? It is. In my question I wrote "It is caused by the std::endl in main()". Meaning, that behaviour only appears when the endl is present in main(). – lo tolmencre Jul 04 '15 at 05:03
  • 1
    @lotolmencre FYI, compiling with gcc 4.9.2 prints the address with and without using `std::endl` in the `main` function. – James Adkison Jul 04 '15 at 05:05
  • @lotolmencre then you're asking about behavior that you haven't described. I don't want to guess how your program behaves without the `std::endl`. Why do you want us to guess? – Drew Dormann Jul 04 '15 at 05:07
  • 1
    @lotolmencre Try `std::cout << std::cout << std::endl;` and you should see you get the same exact address. Why removing `std::endl` from the `main` function changes the behavior is a different issue. – James Adkison Jul 04 '15 at 05:12
  • What then is the proper way to do this? Because std::ostream& operatpr<<() didn't display this behavior whenever I implemented it. What is different about this? – lo tolmencre Jul 04 '15 at 05:16
  • 1
    nvm, I think I figured it out. operator<< takes the stream on teh left as a parameter and writes to it. stuff() writes also to the parameter stream but then sends that streams address to itself. Thanks guys. – lo tolmencre Jul 04 '15 at 05:22