Why are bitwise shifts (<< and >>) used for cout and cin?
Question is in the title really; I'm sure there is something logical, but for now I'm stumped!
According to §8.3.1 of The Design and Evolution of C++:
The idea of providing an output operator rather than a named output function was suggested by Doug McIlroy by analogy with the I/O redirection operators in the UNIX shell (>, >>, |, etc.)
[...]
Several operators were considered for input and output operations: the assignment operator was a candidate for both input and output, but it binds the wrong way. That is
cout=a=b
would be interpreted ascout=(a=b)
, and most people seemed to prefer the input operator to be different from the output operator. The operators<
and>
were tried, but the meanings "less than" and "greater than" were so firmly implanted in people's minds that the new I/O statements were for all practical purposes unreadable (this does not appear to be the case for<<
and>>
). Apart from that, '<' is just above ',' on most keyboards, and people were writing expressions like this:cout < x , y, z;
It is not easy to give good error messages for this.
Maybe because it looks similar to the Unix append operation, as you are essentially appending to an input/output stream?
E.g.
Output
echo "foo" >> bar
Input
sendmail -f [email protected] << myemail.txt
(Stole input example from Zac Howland)
From "The C++ Programming language". Stroustrup's(language authors) words:
Overloading the operator
<<
to mean ‘‘put to’’ gives a better notation and lets the programmer output a sequence of objects in a single statement.But why
<<
? It is not possible to invent a new lexical token . The assignment operator was a candidate for both input and output, but most people seemed to prefer to use different operators for input and output. Furthermore, = binds the wrong way; that is, cout=a=b means cout=(a=b) rather than (cout=a)=b . I tried the operators<
and>
, but the mean ‘‘less than’’ and ‘‘greater than’’ were so firmly implanted in people’s minds that the new I/O statements were for all practical purposes unreadable.
So you remember that if you think cin
as a keyboard and cout
as a monitor, what you type goes into the variable
cin>>var;
Or the contents of your variable goes towards the screen
cout<<var;
>>
and <<
are just operators and you can implement your own >>
and <<
for your classes.
I suppose "somebody" selected them because: a) they are similar to shell file operations and b) to reuse existing operators because there are no need to create new ones