Reputation: 65
Recently I've been watching "Intro to C++" videos, some of which do a better job of explaining certain concepts than others. However, there is something none of the videos have addressed and that is the meaning of the carrot brackets.
Ex:
int main(){
cout << "Hello World" << endl;
return 0;
}
I'm only interested in the first line of the above function. If I'm understanding correctly, cout prints the variable or value that follows, while endl indicates the end of the line while representing "\n"
.
I've googled C++ operators and keywords, and this appears in the lists of neither, although << apparently also serves as a binary left shift operator...
To clarify I'm coming from a Python/Java background so I'd expect a comma or addition sign. I want to know if << is the equivalent of these or does something similar but different.
Thanks.
Upvotes: 0
Views: 1127
Reputation: 16116
In the semantic context of streams, <<
is called the "stream insertion operator" and >>
is called the "stream extraction operator. Syntactically, they are the same as the left and right shift operators that semantically operate on integers.
From the context of Java, you should be familiar with this with the +
operator, which acts differently depending on whether its arguments are ints, floats, or strings (although C++ allows general overloading).
std::endl
differs from '\n'
in that it also flushes the stream (note that std::cout
is line-buffered by default if it is going to a terminal).
Using a +
for output means that a bunch of unnecessary temporary strings would be created, and overloading ,
(like &&
or ||
) would be surprising since it would hide the builtin meaning.
If variadic templates had been available when C++ was in its early stages, it likely would not have used <<
, but a member function.
Upvotes: 4
Reputation: 96430
These are not "carrot brackets". <<
is left-bitshift operator and nothing more.
You can print stuff using <<
because C++ allows you to change how operators behave with specific classes. This is called operator overloading. <<
is overloaded for std::cout
to behave as a printing function.
Upvotes: 6
Reputation: 19213
C++ allows operator overloading so the meaning of <<
changes depending on the types involved. cout
is of type ostream
which overloads <<
to write to the stream.
Here is a listing of many of them note that it isn't a complete list because you can have operators defined outside of the ostream
class as in this example on MSDN of a Date.
Upvotes: 4