Why hasn't my variable changed after applying a bit-shift operator to it?
int main()
{
int i=3;
(i << 1);
cout <开发者_开发问答;< i; //Prints 3
}
I expected to get 6 because of shifting left one bit. Why does it not work?
Because the bit shift operators return a value.
You want this:
#include <iostream>
int main()
{
int i = 3;
i = i << 1;
std::cout << i;
}
The shift operators don't shift "in place". You might be thinking of the other version. If they did, like a lot of other C++ binary operators, then we'd have very bad things happen.
i <<= 1;
int a = 3;
int b = 2;
a + b; // value thrown away
a << b; // same as above
You should use <<=
or the value is just lost.
You're not assigning the value of the expression (i << 1);
back to i
.
Try:
i = i << 1;
Or (same):
i <<= 1;
You need to assign i
to the shifted value.
int main()
{
int i=3;
i <<= 1;
cout << i; //Prints 3
}
Alternatively, you can use <<= as an assignment operator:
i <<= 1;
Because you didn't assign the answer back to i.
i = i << 1;
You need to reassign the value back to i
with i<<=1
(using "left shift and assign operator")
Reason:
i << 1
produce an intermediate value which is not saved back to variable i
.
// i is initially in memory
int i=3;
// load i into register and perform shift operation,
// but the value in memory is NOT changed
(i << 1);
// 1. load i into register and perform shift operation
// 2. write back to memory so now i has the new value
i = i << 1;
For your intention, you can use:
// equal to i = i << 1
i <<= 1;
精彩评论