Does bit shift operator changes the operands?

I am a little confused by bit shift like ">>" or "<<".

See following commands:

int a = 16;
int b;

a>>1;
b = a>>1;

My question is:

what is value of a and b?

Thanks in advance.
Last edited on
No, bit shift does not change the operands.
a == 16
b == 8

a >> 1; doesn't change the value of a. You need to store the shifted value back into a: a >>= 1;
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <iomanip>

int main()
{
    int a = 16;
    int b;

    a>>1;
    b = a>>1;

    std::cout << "a=0x" << std::hex << a << " b=0x" << std::hex << b << std::endl;
}
The confusion here is that << and >> do change the operands when used as insertion/extraction operators (ie: cin/cout). But they do not change either operands when used as bitshift operators.

Another reason why I really dislike the overloading of >>/<< for iostream: overloading an operator to do something completely different than what it does originally.
Last edited on
I hadn't thought of that.

I recently discovered that boost::path appends with /, it took me forever to work it out.

I do wish they'd stop being cool when designing these features.
Last edited on
Topic archived. No new replies allowed.