Rupert Madden-Abbott Rupert Madden-Abbott - 3 months ago 15
C Question

warning: left shift count >= width of type

I'm very new to dealing with bits and have got stuck on the following warning when compiling:


7: warning: left shift count >= width of type



My line 7 looks like this

unsigned long int x = 1 << 32;


This would make sense if the size of
long
on my system was 32 bits. However,
sizeof(long)
returns
8
and
CHAR_BIT
is defined as
8
suggesting that long should be 8x8 = 64 bits long.

What am I missing here? Are
sizeof
and
CHAR_BIT
inaccurate or have I misunderstood something fundamental?

Answer

long may be a 64-bit type, but 1 is still an int. You need to make 1 a long int using the L suffix:

unsigned long x = 1UL << 32;

(You should also make it unsigned using the U suffix as I've shown, to avoid the issues of left shifting a signed integer. There's no problem when a long is 64 bits wide and you shift by 32 bits, but it would be a problem if you shifted 63 bits)