strange bit-shifting

Stefan Farfeleder stefan at fafoe.narf.at
Tue Apr 3 18:19:53 UTC 2007


On Tue, Apr 03, 2007 at 08:22:15PM +0300, Andriy Gapon wrote:
> 
> $ cat test_shl.c
> #include <stdint.h>
> #include <stdio.h>
> 
> int main()
> {
>         uint64_t l;
> 
>         l = 0;
>         l--;
>         printf("%.16lX\n", l);
>         l <<= 64;
>         printf("%.16lX\n", l);
>         return 0;
> }
> 
> $ cc test_shl.c -o test_shl
> test_shl.c: In function `main':
> test_shl.c:11: warning: left shift count >= width of type
> $ ./test_shl
> FFFFFFFFFFFFFFFF
> FFFFFFFFFFFFFFFF
> $ uname -srm
> FreeBSD 6.2-RELEASE-p2 amd64
> $ gcc -v
> Using built-in specs.
> Configured with: FreeBSD/amd64 system compiler
> Thread model: posix
> gcc version 3.4.6 [FreeBSD] 20060305
> 
> What gives ? It looks like shift is actually done not by specified
> number of bits but by that number modulo 64.
> Please also mind that the same thing happens if I use a variable instead
> of a constant in that expression.

The behaviour is undefined and you even got a warning from GCC.

C99 6.5.7:

# 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.

Stefan


More information about the freebsd-hackers mailing list