Say I want to print some values. I am assuming that I should get Integer Overflow if my signed variable exceeds from TMin
and TMax
(in this case, using 4 byte int, 0x7FFFFFFF
as Tmax
and 0x80000000
as Tmin
) but in these example I am not getting what I expect (explained in comments):
// Tmax = 0x7FFFFFFF == 2147483647
// Tmin = 0x80000000 == -2147483648
printf("1- overflow test: %d\n", 0x7FFFFFFF+1 ); // overflow - how compiler finds out it's a signed value, not an Unsigned one
printf("2- overflow test: %d\n", 0x80000000-1 ); // in contrast, why I am not getting an integer overflow here
printf("3- overflow test: %d\n", (int) 0x80000000-1 ); // overflow (Expected)
printf("4- overflow test: %d\n",(int) (0x7FFFFFFF+1)); // overflow (Expected)
OP is not always experiencing signed integer overflow - which is undefined behavior.
The following is unsigned math as
0x80000000
is likely an unsigned integer. Hexadecimal constants are of the type that first fits themint, unsigned, long, unsigned long, ...
0x80000000-1
is an unsigned type as0x80000000
first fits in an unsigned type, likelyunsigned
with the value of2147483648u
.2147483648u - 1
-->2147483647u
.0x7FFFFFFF+1
is a signed type as0x7FFFFFFF
first fits in a signed type, likelyint
with the value ofINT_MAX
.int
+int
-->int
andINT_MAX + 1
--> overflow.OP said "0x80000000 as Tmin" is certainly a mis-understanding. In C, with 32-bit
int/unsigned
,0x80000000
is a hexadecimal constant with the value of2147483648
. For OP, Tmin is more likely-INT_MAX - 1
.