【问题标题】:What is unsigned type we pass to parameter?我们传递给参数的无符号类型是什么?
【发布时间】:2012-06-09 09:23:39
【问题描述】:

我有以下代码的练习

int FindFirstSet(unsigned BitMap, unsigned start)
{
    unsigned Mask = (1 << start);
    while (Mask)
    {
        if (BitMap & Mask) return start;
        ++start;
        Mask <<= 1;
    }
    return -1;
}

问题是:

"C++ 编程语言并没有指定无符号数有多少位 整数。解释为什么上面的代码不管在 无符号整数。”

按照这个问题,我会不会认为:任何类型的“位图参数”都是,“开始参数”也有位图的类型?

【问题讨论】:

    标签: c++ types unsigned


    【解决方案1】:

    所有参数和变量都是无符号整数。

    【讨论】:

    • 哦,非常简单的答案,但它是正确的;),非常感谢?
    【解决方案2】:

    此代码将起作用,因为MaskBitMap 具有相同的长度,并且start 的最大可能值大于BitMap 的长度。

    但此代码并不总是按预期工作。以下是 c++ 标准对移位运算符的说明: The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

    因此,在某些编译器上,我们可能会看到FindFirstSet(1, 42) 返回 42 而不是 -1。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-16
      • 2018-01-23
      • 2014-10-03
      • 1970-01-01
      • 2012-01-03
      • 2021-08-17
      • 1970-01-01
      相关资源
      最近更新 更多