问题
In C,
unsigned int size = 1024*1024*1024*2;
which results a warning "integer overflow in expression..." While
unsigned int size = 2147483648;
results no warning?
Is the right value of the first expression is default as int? Where does it mention in C99 spec?
回答1:
When using a decimal constant without any suffixes the type of the decimal constant is the first that can be represented, in order (the current C standard, 6.4.4 Constants p5):
- int
- long int
- long long int
The type of the first expression is int
, since every constant with the value 1024 and 2 can be represented as int. The computation of those constants will be done in type int, and the result will overflow.
Assuming INT_MAX equals 2147483647 and LONG_MAX is greater than 2147483647, the type of the second expression is long int
, since this value cannot be represented as int, but can be as long int. If INT_MAX equals LONG_MAX equals 2147483647, then the type is long long int
.
回答2:
unsigned int size = 1024*1024*1024*2;
This expression 1024*1024*1024*2
(in the expression 1024
and 2
are of type signed int
) produces result that is of type signed int
and this value is too big for signed int
. Therefore, you get the warning.
After that signed multiplication it is assigned to unsigned int
.
来源:https://stackoverflow.com/questions/37606564/what-is-the-default-data-type-of-number-in-c