Reputation: 137
I am trying to assign a number to unsigned int, but it results in an error. I thought as long as the number is between 0 and 2^32, it should work. Here is my code.
unsigned int number = 4026658824;
However, I get this error.
error: constant promoted according to the 1999 ISO C standard
Upvotes: 2
Views: 1761
Reputation: 121387
Type of decimal constant depends on the type in which it can be represented, per 6.4.4.1 Integer constants:
The type of an integer constant is the first of the corresponding list in which its value can be represented.
(See the table in the link for how C language says the actual type of integer constants is deduced).
Typically a signed int can't represent the value 4026658824
. So, 4026658824
probably has type long int
or long long int
on your system. If unsigned int
can be represent 4026658824
then this is fine but your compiler is being cautious.
You could use u
or U
suffix or cast it to unsigned int
. The suffix u
may not work if the integer constant has bigger value. For example, if 17179869184u
can't be represented by unsigned int
then its type may be unsigned long int
or unsigned long long int
and you may still get diagnostics about it.
Upvotes: 5
Reputation: 2983
In addition to the answers above, if you want a variable to definitely be a certain number of bits, use Fixed-width integer types. Doing embedded work we have to be careful of this (CPU may only be 8 or 16-bit) so pretty much always use them for everything.
Upvotes: 0