79

Question is in the title really; I'm sure there is something logical, but for now I'm stumped!

Yi Jiang
  • 46,385
  • 16
  • 133
  • 131
Crowstar
  • 811
  • 1
  • 6
  • 6
  • 11
    I think it's because they resemble arrows suggesting the flow of some substance. – Pointy Jan 31 '11 at 17:55
  • 1
    Just guessing, but I imagine it's because you're "shifting" data in from or out to a file. – Mark Ransom Jan 31 '11 at 17:55
  • Given the other possible choices of operators, @Crowstar, is there a pair that you think would have been a better choice? – Pointy Jan 31 '11 at 17:56
  • 9
    For completeness' sake: these are called insertion operators in this context: http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/ – ChristopheD Jan 31 '11 at 17:57
  • 6
    @Pointy: how about functions like `read()` and `write()`? I think user-defined operators should have similar semantics as the built-in operators, e.g., `+` could be used to add complex numbers or geometrical vectors. But `ostream::operator< – Philipp Jan 31 '11 at 18:03
  • @Phillip well I don't know if I would *defend* the decision, but it's not at all hard for me to understand why "<>" would seem like good ideas. – Pointy Jan 31 '11 at 18:07
  • 1
    @Crowstar: may I reverse the question ? Why are insertion and extraction operators used for bit-wise shifting ? Personally I use streams more often than bitwise manipulation ;) – Matthieu M. Jan 31 '11 at 20:04
  • 1
    @Matthieu M. I work on low level. I personally use bitwise manipulation more often then streams :P – Federico klez Culloca Feb 01 '11 at 06:07
  • @MatthieuM. well that would be kinda silly, considering that the bitwise manipulation surely dates back to C... – MFH Jul 04 '12 at 20:24
  • @MFH: So the question is, did C preceded the shell IO redirection ? – Matthieu M. Jul 05 '12 at 06:09
  • @MatthieuM. Good question! When did shell redirections first appear? On UNIX, Multics or even before those? – MFH Jul 05 '12 at 15:20
  • I don't think shell redirection has anything to do with it. In the context where `<>` were overloaded, the authors were in the process of defining the language. Changing the meaning of an operator, especially a little used operator (at least in most programming contexts) was acceptable. – James Kanze Dec 11 '12 at 17:17

13 Answers13

67

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 as cout=(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.

Jerry Coffin
  • 437,173
  • 71
  • 570
  • 1,035
18

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 test@domain.com << myemail.txt

(Stole input example from Zac Howland)

Abe Voelker
  • 25,576
  • 13
  • 76
  • 95
  • 1
    @Federico: actually, it does. You use `< – Zac Howland Jan 31 '11 at 18:07
  • @Zac thanks for the example; I added it to the answer to make it more complete – Abe Voelker Jan 31 '11 at 18:11
  • 1
    This is my preferred explanation. I just hate how C++ advocates changing the meaning of operators. I try to stay away from ANY library or code that changes that meaning. I.E. MyWebRequest = "http://www.google.com"; actually downloading the web page through an assignment. And although I understand the need for it, I think operator overloading gets abused way too much. I would have much preferred they used something like so as to not change the meaning OR change the bit shift operator to something else. – Rahly Aug 24 '16 at 00:19
  • @rahly: But the token `->` already has an existing meaning as well, and so does the token pair ` – Ben Voigt Sep 11 '16 at 18:09
  • You are right... but my point was not to change the meaning of existing operators.... maybe :> and <:.... auto="" has="" meaning="" no="" real="" tmp="myvar"> – Rahly Sep 11 '16 at 18:17
11

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.

UmmaGumma
  • 5,633
  • 1
  • 28
  • 45
7

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;
Federico klez Culloca
  • 22,898
  • 15
  • 55
  • 90
7

>> 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

Elalfer
  • 5,146
  • 18
  • 24
6

Because they had more or less a reasonable precedence and looked good. In C++ you cannot create new operators or change their precedence or grouping rules, you can only overload existing ones and changing what they actually do.

The choice of << and >> has some unfortunate side effect because it's somehow pushing the idea that the output will be done respecting the order. While this is true for the actual output thanks to a clever chaining trick it's however false for the computations involved and this is very often surprising.

To be more specific writing

std::cout << foo() << bar() << std::eol;

does NOT imply that foo will be called before bar.

EDIT

With C++17 the sequence problem has been "fixed". Now the order of evaluation is specified to be left-to-right for << and >> operators. There are still places in C++ where the order of evaluation is unspecified (or even non-existing meaning that evaluation can be interleaved) but a few common cases now behave in a predictable and portable way see this answer .

6502
  • 104,192
  • 14
  • 145
  • 251
  • But who cares? If you're using functions with side effects in an output statement, you're creating unreadable and unmaintainable code anyway. (Otherwise, of course, the argument holds for many other cases as well. And there is a good argument for imposing the order---making errors reproduceable, when you make a mistake and do get a side effect.) – James Kanze Dec 11 '12 at 17:20
  • 1
    @JamesKanze: I've simply found that many C++ programmers do think that in the example code `foo()` is guaranteed to be called before `bar()`... and they write code like `s << header() << body() << footer();` where `body()` computes some totals used in `footer()`. This kind of error is less frequent for function parameters instead. – 6502 Dec 11 '12 at 18:04
  • I wouldn't hire a programmer who wrote code like this, even if the order was guaranteed. Hidden dependencies like that are a real maintenance nightmare. – James Kanze Dec 11 '12 at 19:30
  • 3
    @JamesKanze: That comment sounds comic (please remember that you're talking about a library with horrors like `setw` and `setfill` in it). – 6502 Dec 11 '12 at 23:00
4

They are not bitwise operators, They are called insertion and extraction operators in this context.

http://www.cplusplus.com/doc/tutorial/basic_io/

These are used only for visual interpretation. If you study developing own stream and operator overloading, then you can see that you can even use + for input and - for output :)

Sarwar Erfan
  • 17,604
  • 5
  • 41
  • 55
4

Mostly because of their associativity. The insertion and extraction operators associate from left to right, so

std::cout << "Hello" << ' ' << 4 << 2;

evaluates as you'd expect: first with "Hello", then with ' ' and finally with 4 and 2. Granted, the addition operator, operator+ also associates from left to right. But that operator and others with left-to-right associativity already have a different meaning.

wilhelmtell
  • 53,297
  • 19
  • 89
  • 128
3

This answer is unsatisfying but correct: they aren't bitwise operators.

The meaning of the operator is determined by the data-type that appears on its left. In the case of cin and cout (and other stream types) << and >> operators move values to and from streams. In the case that the left operand is an integer, the operation is the bitwise operation that you already know from C.

The meaning of the operator is not fixed, although its precedence is.

Kevin A. Naudé
  • 3,808
  • 17
  • 19
1

Bjarne chose them for practical precedence, associativity and mnemonic value.

The precedence isn't perfect, e.g. the boolean and bit-level operators are troublesome.

But it's fairly OK.

Cheers and hth. - Alf
  • 135,616
  • 15
  • 192
  • 304
1

Insertion operator >> and << are used with Input Stream and Output Stream respectively because Input stream means flow of data into your program and Output stream means flow of data out of your program. As these insertion operators look like Directional operator (Showing direction of flow of data), so >> is chosen for Input stream and << for the Output stream.

Have a look at the part of code...

int Num1;
cin >> Num1;

here if you observe carefully >> is showing flow of data to variable (declared in program) that means the flow of data to the program , which is a job of Input stream (here cin).

similarly goes with cout,

int Num2 = 5;
cout << Num2;

Here << showing the flow of data out of the program (as Num2 is part of the program), which is the job of Output stream.

I hope all this make sense to you.

mindriot
  • 4,823
  • 22
  • 34
Gopal Sharma
  • 355
  • 3
  • 11
  • 1
    Hi! Welcome to StackOverflow. I just submitted an edit marking up your code (it's in review). You can indent it by using the `{}` button, or by indenting by four spaces. You can also mark up inline code with backticks (\`). – rrauenza Jun 01 '16 at 19:24
0
cout << "Output sentence"; // prints Output sentence on screen
cout << 120;               // prints number 120 on screen
cout << x;                 // prints the content of x on screen 

The << operator inserts the data that follows it into the stream preceding it. In the examples above it inserted the constant string Output sentence, the numerical constant 120 and variable x into the standard output stream cout.

The standard input device is usually the keyboard. Handling the standard input in C++ is done by applying the overloaded operator of extraction (>>) on the cin stream. The operator must be followed by the variable that will store the data that is going to be extracted from the stream. For example:

int age;
cin >> age;
ayush
  • 13,272
  • 9
  • 49
  • 95
0

I assume that you are aware that C++ allows for operator overloading. In general, you overload operators only if the semantics are completely transferable (e.g. overloading the addition for a vector class to add two vectors together). I think your question refers to why one would use bitshift operators, overload them for the iostream, and give them a completely different meaning than their original purpose. The reason it can be done is because bitshift operations are so far removed from what iostreams do that no one could be confused into thinking that << or >> is doing a bitshift on an iostream. And the reason why they are convenient to use also is that their ordering is to evaluate the operand on the left first, then the one on the right, and do the operation. This fits to what you would want to happen when you are using the operators to append or extract stuff from an iostream.

But, to the original question, why? I don't really know, it just seems to me like the << and >> are pretty easily understood as taking information from one entity and putting it in the other. Why does the reason need to be more complicated than that? It looks sensible to use those because their meaning is obvious.. what better could you ask of an operator?

Mikael Persson
  • 16,908
  • 6
  • 34
  • 49
  • 4
    -1: The order of evaluation of left and right side of `<>` is not guaranteed. This is indeed sometimes source of bugs when people writes things like `s << foo() << bar()` and expects `foo` being called before `bar`. What is guaranteed is that the result of `foo` will be sent to the stream before the result of `bar` but the computation order is NOT guaranteed. Only `,`, `||` and `&&` binary operators give such a guarantee... and that guarantee anyway is only present if you don't overload them. – 6502 Feb 01 '11 at 10:49