Cannot understand shift operator behavior in C code -
Cannot understand shift operator behavior in C code -
look @ sample c code (extracted test case example):
main() { unsigned long a, b; int c; c = 32; = 0xffffffff << 32; b = 0xffffffff << c; printf ("a=%x, b=%x\n", a, b); }
prints: a=0, b=ffffffff
i cannot understand why b not zero, a. tested on microsoft c , gcc.
update: fixed stupid typo (should have been << c , not << b of course). question still stands, e.g. result still same.
in c undefined behavior left shift more width of promoted operand.
(c99, 6.5.7p3) "if value of right operand negative or greater or equal width of promoted left operand, behavior undefined."
the c rules types of integer constant different between c89 , c99.
i assume in examples below int
, unsigned int
types 32-bit.
in c99
the type of unsuffixed hexadecimal integer constant first in corresponding list in value can represented: int
, unsigned int
, long
, unsigned long
, long long
, unsigned long long
.
so here 0xffffffff
of type unsigned int
, 0xffffffff << 32
undefined behavior.
in c89
the type of unsuffixed hexadecimal integer constant first in corresponding list in value can represented: int
, long
, unsigned long
0xffffffff
of type unsigned long
, if unsigned long
32-bit , of type long
if long
64-bit (or larger).
and 0xffffffff << 32
undefined behavior, if unsigned long
, long
32-bit.
c bit-shift
Comments
Post a Comment