问题
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?
回答1:
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
回答2:
You should use <<=
or the value is just lost.
回答3:
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;
回答4:
Because you didn't assign the answer back to i.
i = i << 1;
回答5:
You're not assigning the value of the expression (i << 1);
back to i
.
Try:
i = i << 1;
Or (same):
i <<= 1;
回答6:
You need to reassign the value back to i
with i<<=1
(using "left shift and assign operator")
回答7:
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;
来源:https://stackoverflow.com/questions/6367379/why-hasnt-my-variable-changed-after-applying-a-bit-shift-operator-to-it