为什么我的变量在应用位移运算符后没有更改?

Why hasn't my variable changed after applying a bit-shift operator to it?

本文关键字:运算符 变量 我的 应用 为什么      更新时间:2023-10-16
int main()
{
    int i=3;
    (i << 1);
    cout << i; //Prints 3
}

由于向左移动了一点,我本以为会得到6分。为什么它不起作用?

因为位移位运算符返回一个值。

你想要这个:

#include <iostream>
int main()
{
     int i = 3;
     i = i << 1;
     std::cout << i;
}

轮班操作员没有"就地"轮班。你可能在考虑另一个版本。如果他们真的这样做了,就像许多其他C++二进制运算符一样,那么我们就会发生非常糟糕的事情。

i <<= 1; 
int a = 3;
int b = 2;
a + b;    // value thrown away
a << b;   // same as above

您应该使用<<=,否则值就会丢失。

您没有将表达式(i << 1);的值赋值回i

尝试:

i = i << 1;

或者(相同(:

i <<= 1;

您需要将i分配给移位后的值。

int main()
{
    int i=3;
    i <<= 1;
    cout << i; //Prints 3
}

或者,您可以使用<lt;=作为分配操作员:

i <<= 1;

因为您没有将答案分配回i。

i = i << 1;

您需要使用i<<=1(使用"左移和赋值运算符"(将值重新分配回i

原因:CCD_ 7产生中间值,该中间值不被保存回变量CCD_。

// 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;

出于您的意图,您可以使用:

// equal to i = i << 1
i <<= 1;
相关文章: