Reputation: 10068
I'm currently studying C programming language by following the book "C primer plus".
In the section on overflow, the author states
minimum range for long is
–2,147,483,647 to 2,147,483,647
, corresponding to a 32-bit unit.
I was wondering, shouldn't the max value for a 32 bit unit be 2,147,483,648
and not 2,147,483,647
as stated by the author?
I have also seen on tutorial point that the range for a 32 bit unit is –2,147,483,648 to 2,147,483,647
. I'm extremely confused.
Also, when I run the code
int i = 2147483647;
printf("%d %d %d\n", i, i+1, i+2);
I got the result 2147483647 -2147483648 -2147483647
, which support that the range of 32 bit unit is –2,147,483,648 to 2,147,483,647
. So which one is correct?
PS - I have studied two's complement system previous, and from what I can remember, the max number should always be the -(min number) + 1
, so from the two's complement system, I was thinking that –2,147,483,647 to 2,147,483,648
is more likely to be correct. But the printf
above seem to support –2,147,483,648 to 2,147,483,647
, and both are different to what the author stated –2,147,483,647 to 2,147,483,647
.
Upvotes: 3
Views: 914
Reputation: 11
–2,147,483,648 to 2,147,483,647 plus ZERO. Simply put, you forgot to count the ZERO.
Upvotes: 0
Reputation: 154592
32-bits of memory can encode, at most, 232 different values.
C integers consists of 3 parts: sign bit, values bits and rarely padding bits. For this answer, assume the number of padding bits is zero.
C supports 3 integer encodings: 2's complement, 1's complement, sign magnitude.
A 32-bit integer then has the range of
[–2,147,483,648 ... 2,147,483,647]
Most common by far[–2,147,483,647 ... 2,147,483,647]
1 smaller range than 2's[–2,147,483,647 ... 2,147,483,647]
1 smaller range than 2'sAll 3 then meet the C requirement for a long
:
Their implementation-defined values shall be equal or greater in magnitude (absolute value) to those shown, with the same sign.
- minimum value for an object of typelong int
LONG_MIN
-2147483647
- maximum value for an object of typelong int
LONG_MAX
+2147483647
C11dr §5.2.4.2.1 1
Note that long
as well as int
could be 64-bit and have a much wider range.
I was wondering, shouldn't the max value for a 32 bit unit be 2,147,483,648
2,147,483,648 is not compatible with a 32-bit 2's complement as that would take 33 bits.
Avoid integer overflow in C as it is undefined behavior (UB). OP's text output is not definitive.
int i = 2147483647; // v----v----- UB
printf("%d %d %d\n", i, i+1, i+2);
Instead print the min/max based on <limits.h>
:
printf("int min:%d max:%d\n", INT_MIN, INT_MAX);
printf("long min:%ld max:%ld\n", LONG_MIN, LONG_MAX);
Even if OP's minimum integer is –2,147,483,648, that does not mean that it is the minimum value on all implementations. The C spec only requires –2,147,483,647 or less.
Upvotes: 3