2012-06-09 104 views
1

我有行使下列代码什么是我们传递给参数的无符号类型?

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

的问题是:

“的C++编程语言不指定多少位中有一个无符号 整数解释为什么上面的代码将工作。而不管 无符号整数中的位数“。

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

回答

3

所有参数和变量都是unsigned int。

+0

哦,很简单的答案,但它的正确;),非常感谢你? –

1

此代码将工作,因为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。

相关问题