Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does operator<< refer to the insertion operator and when to the bitwise left shift?

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;
}
like image 945
jmmom Avatar asked Sep 10 '25 03:09

jmmom


2 Answers

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.

like image 165
marcinj Avatar answered Sep 13 '25 01:09

marcinj


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.

like image 33
ralfg Avatar answered Sep 13 '25 01:09

ralfg