2012-06-09 107 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。

相關問題