Saturday, April 27, 2019

c++ - How do the "" operators do I/O?











I'm making a long awaited return to C++ and there's some basic notation that doesn't really seem to be that prominent in other languages.



If you look at this line of code



cout << "firstvalue is " << firstvalue << endl;


I realise what this does. It write's "firstvalue is x" to the console. x being the value of firstvalue. However, I do not know anything about the "<<" or ">>" double angled brackets. I haven't been able to research them or what they do as I don't know the formal name for them.




My question is, what actually happens (step by step) in the above statement? And what are these "<<" for? I think I understand that cout is a standard library function for writing to the console. However I'm used to either objective-c or dot notation. I do not see what object this "cout" function is a member of.



I can understand printf a little more easily, as at least it provides braces for the arguments. e.g. printf("your string here").


Answer



C++ allows operator overloading. That means a user-defined type can define its own behavior on built-in operators. In this case the operators are called: left shift or right shift operators. Those operators have been traditionally been used for bit-shifting, but the standard library repurposes them to symbolize streaming operations.



You can find a list of the available operators in C and C++ here.



In your case you are streaming a string literal and a value of some type into std::cout, which is an object of type std::basic_ostream.




Step-by-Step



After precedence rules have been applied your code looks like this:



((cout << "foobar") << x) << endl;


The compiler will basically transform the object << object expressions into function calls.



operator<<(operator<<(operator<<(cout, "foobar"), x), endl);



Then it will figure out which overload to call. (This is really
tricky. For now it should be sufficient to believe that it simply
looks for an overload of operator<< with matching arguments).



Most of the built-in overloads for basic_ostream are here and here.


No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...