2012-12-04 43 views

回答

5

是的,這是未定義的行爲,根據部分6.5.7第3段

...如果右操作數的值是負的或大於或等於所述推動左的寬度操作數,行爲是未定義的。

+0

謝謝。經過進一步調查後,我發現我的c編譯器需要mod32的數量,然後轉移。 –

+0

如果您的計算機是x86計算機,則它實際上是硬件的一部分,或多或少。 'sal' /'sar' /'shl' /'shr'需要一個立即數或'%cl'寄存器(它只有一個字節),並且它只在移位時使用該值的低5位。 – Cornstalks

+0

@BrandonYates你的處理器很可能是這種行爲的責任。然而,不建立任何未定義行爲可能做的具體期望是一個好習慣。 –

3
ISO c99 : 6.5.7 Bitwise shift operators 

3
The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.

5
The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type or if E1 has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of E1/2E2. If E1 has a signed type and a negative value, the resulting value is implementation-defined

你可以看到C-標準澄清一切。