简体   繁体   中英

Bit Shifting: Shift Count >= Width Of Type

The code below, when compiled, throws a warning caused by line 9:

warning: shift count >= width of type [-Wshift-count-overflow]

However, line 8 does not throw a similar warning, even though k == 32 (I believe). I'm curious why this behavior is occurring? I am using the gcc compiler system.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int bit_shift(unsigned x, int i){
    int k = i * 8;
    unsigned n = x << k; /* line 8 */
    unsigned m = x << 32; /* line 9 */
    return 0;
} 

int main(){
    bit_shift(0x12345678, 4);
    return 0;
}

The value of k in bit_shift is dependent on the parameter i . And because bit_shift is not declared static it is possible that it could be called from other translation units (read: other source files).

So it can't determine at compile time that this shift will always be a problem. That is in contrast to the line unsigned m = x << 32; which always shifts by an invalid amount.

I think why Line 8 does not throw a warning is because left shifting an unsigned int32 >= 32 bits is NOT an undefined behavior .

C standard (N2716, 6.5.7 Bitwise shift operators) says:

The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2^E2, reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM