为什么这两个数字比较相等?

我想知道为什么这两个数字比较相等的情况。我有一个(可能是错误的)意识到我搞砸了我的枚举,因为在我的枚举中我经常这样做:

enum class SomeFlags : unsigned long long { ALL = ~0, FLAG1 = 1, FLAG2 };

我认为 0 是一个 int 并被分配给一个 unsigned long long,这是一个错误。

unsigned long long number1 = ~0;
/* I expect the 0 ( which is an int, to be flipped, which would make it
the max value of an unsigned int. It would then get promoted and be 
assigned that value to an unsigned long long. So number1 should
have the value of max value of unsigned int*/



int main()
{
    unsigned long long number2 = unsigned long long(0);
    number2 = number2 - 1;
    /* Here I expect number2 to have the max value of unsigned long long*/

    if (number1 == number2)
    {
        std::cout << "Is same\n";
        // They are the same, but how???
    }
}

这真的很令人困惑。为了强调这一点:

unsigned long long number1 = int(~0);
/* I feel like I'm saying:
- initialize an int with the value of zero with its bits flipped
- assign it to the unsigned long long

And this somehow ends up as the max value of unsigned long long???*/

回答

cppreference:“的结果operator~是参数的按位非(补码)值(提升后。

然而,这里不需要提升(tointunsigned int)——但是signed用该值翻转类型中的所有位0将使其-1(所有位设置)转换为unsigned类型时将是该类型可以容纳的最大值。

为避免这种情况,请制作0 unsigned. 的结果~0U将是一个unsigned int设置了所有位的,可以unsigned完美地转换为任何更大的类型。

unsigned long long number1 = ~0U;

以上是为什么这两个数字比较相等?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>