The following line declares an int
that happens to be called cout
(it is not the std::cout
stream)
int cout = 5;
The <<
operator peforms a bit shift.
So
cout << cout;
is only performing a bit shift and not storing the result.
To clarify, have a look at the following program:
#include<iostream>
int main()
{
int cout = 5;
auto shiftedval = cout << cout;
std::cout << "cout's value is " << cout << ", and the result of the bit shift is " << shiftedval << '\n';
return 0;
}
It will output:
cout's value is 5, and the result of the bit shift is 160
What is happening behind the scenes is that operator<<
has been overloaded to take an ostream
on the left hand side.
By including iostream
you get this function and the compiler will know what you mean if you have an ostream
to the left of the <<
operator.
Without a library the <<
would just simply have been a bitwise shift operator.
Also note that if you had ill-advisedly included using namespace std;
or using std::cout
then cout
would then mean ostream
and <<
would trigger a call to the library operator<<
function. If after adding the using
declaration above you include another declaration of cout
the newly declared name will hide the previous declaration and cout
will now be considered an int
again and we're back to the bit shift operator functionality being used.
Example:
#include<iostream>
using namespace std; // using std:: at global scope
int main()
{
int cout = 5;
auto shiftedval = cout << cout;
//the following will not compile, cout is an int:
cout << "cout's value is " << cout << ", and the result of the bit shift is " << shiftedval << '\n';
//but we can get the cout from the global scope and the following will compile
::cout << "cout's value is " << cout << ", and the result of the bit shift is " << shiftedval << '\n';
return 0;
}