C++: Compiler warning for large unsigned int

gruszczy picture gruszczy · Feb 28, 2010 · Viewed 16.2k times · Source

I have following array, that I need to operate by hand on bitmaps.

const unsigned int BITS[32] = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 
                               2048, 4096, 8192, 16384, 32768, 65536, 131072, 
                               262144, 524288, 1048576, 2097152, 4194304, 
                               8388608, 16777216, 33554432, 67108864, 134217728, 
                               268435456, 536870912, 1073741824, 2147483648};

Unfortunately, when compiled I get

warning: this decimal constant is unsigned only in ISO C90

How can I remove this?

Answer

Brooks Moses picture Brooks Moses · Feb 28, 2010

Integer literals in C are, by default, of type "signed int" (edit: but see comments for caveats). The last number there is too large to be represented as a signed 32-bit integer, and so you need to tell the compiler that it's an unsigned integer by suffixing it with "U", as:

2147483648U

Note that you can also add a suffix of "L" to make it a "long", but on many systems that's still 32-bit and thus irrelevant.

Also, there's a much less error-prone (and easier-to-read) way to write this code, with the bit-shift operator:

const unsigned int BITS[32] = {1U, 1U<<1, 1U<<2, 1U<<3, 1U<<4,
                               /* and so on */
                               1U<<31};

Or, writing in hexadecimal, if you don't like bit shifts for some reason:

const unsigned int BITS[32] = {0x1, 0x2, 0x4, 0x8, 0x10, 0x20,
                               /* and so on */
                               0x80000000U};