1 << 31 and related issues

Eitan Adler lists at eitanadler.com
Mon Nov 25 19:48:41 UTC 2013


There are a few cases in FreeBSD where the expression (1 << 31) is used.

However this produces undefined behavior as '1' is of type int.  (see
6.4.4p5: The type of an unmarked integer constant is the first of the
following list in which its value can be represented: int, long int,
long long int).  The shift of 31 is illegal (see 6.5.7p4) if the size
of an int is 32.  The same issue arises with 2 << 30 and 3 << 30.

I have been working on fixing this issue in a few different projects.
The correct fix here is to use 1U as the literal instead.  adrian@ has
advocated for the macros BIT32(bit) and BIT64(bit) which I would also
support.

I have patches which fix the issue by using 1U in these cases.  I did
not change non-broken cases.  I also did not change contributed code.

An incomplete listing of the issues available here:
http://people.freebsd.org/~eadler/files/1..31.txt

-- 
Eitan Adler


More information about the freebsd-arch mailing list