When does operator <<
refer to the insertion operator and when does it refer to the bitwise left shift?
This will output 10
, and operator <<
refers to the left shift.
cout << a.b() << a.a.b << endl;
And this will output 11
, operator <<
refers to the insertion operator.
cout << a.b();
cout << a.a.b ;
I am confused, when will operator <<
(when use with cout
) refer to the left shift operator?
#include <iostream>
using namespace std;
class A {
public:
A() { a.a = a.b = 1; }
struct { int a, b; } a;
int b();
};
int A::b(){
int x=a.a;
a.a=a.b;
a.b=x;
return x;
};
int main(){
A a;
a.a.a = 0;
a.b();
cout << a.b() << a.a.b << endl; // ?????
return 0;
}
This will output 10, and operator<< refer to left shift.
cout << a.b() << a.a.b << endl;
This is caused of the fact that order of evaluation of operands is unspecified. With clang it outputs 11 but with gcc it outputs 10.
Your code:
cout << a.b() << a.a.b << endl;
can be replaced with:
std::cout.operator<<(a.b()).operator<<(a.a.b);
clang first evaluates a.b()
then a.a.b
, g++ does it the other way around. Since your a.b()
modifies variables you get different results.
When you rewrite your code as:
cout << a.b();
cout << a.a.b ;
then you have two full expression statements, there is no unspecified behaviour here related to operand evaluation. So you get always the same result.
The problem you are confronted with is not concerning the << operator. In each case, the insertion operator is called.
However, you are faced with a problem concerning the order of evaluation in the command line
cout << a.b() << a.a.b << endl;
The function a.b()
has a side effect. It swaps the values a.a.a and a.a.b. Thus, it is evident, wether a.b() is called before or after evaluating the value ov a.a.b
.
In C++, the order of evaluation is unspecified, see cppreference.com for a more detailed discussion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With