C++: Compiler warning for large unsigned int
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?
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};
Your constant has to be specified as unsigned too, use
2147483648UL
(UL = Unsigned Long), or simply
2147483648U
for an unsigned int.
As your code is right now, a constant, which is by default a plain int
, and hence signed, is assigned to an unsigned int
, which generates your warning.
Not necessary to define data type as unsigned just type;
int variable_name=2147483648U;
else just convert decimal value to hex...
精彩评论