Using stdint.h from glibc (gcc SUSE Linux version 9.2.1, Intel Core I7 processor) I came across a most strange behaviour when printing INT32_MIN directly:
#include <stdio.h>
#include <stdint.h>
void main(void)
{
printf("%d\n", INT16_MIN);
int a = INT16_MIN;
printf("%d\n", a);
printf("%ld\n", INT32_MIN);
long b = INT32_MIN;
printf("%ld\n", b);
printf("%ld\n", INT64_MIN);
long c = INT64_MIN;
printf("%ld\n", c);
}
which outputs:
-32768
-32768
2147483648
-2147483648
-9223372036854775808
-9223372036854775808
Furthermore, if I try
printf("%ld\n", -INT32_MIN);
I get the same result, but with compiler warning: integer overflow in expression '-2147483648' of type 'int' results in '-2147483648' [-Woverflow].
Not that this is incredibly bad for any existing program, actually it seems pretty harmless, but is this a bug in good old printf?
No.
There is an easy way for this to happen. The second integer/pointer argument to a function should be passed in 64-bit register RCX.
INT32_MINis a 32-bitintwith bit pattern 0x80000000, since that is the two’s complement pattern for −2,147,483,648. The rules for passing a 32-bit value in a 64-bit register are that it is passed in the low 32 bits, and the high bits are not used by the called routine. For this call, 0x80000000 was put into the low 32 bits, and the high bits happened to be set to zero.Then
printfexamines the format string and expects a 64-bitlong. So it goes looking in RCX for a 64-bit integer. Of course, the rules for passing a 64-bit integer are to use the entire register, soprintftakes all 64 bits, 0x0000000080000000. That is the bit pattern for +2,147,483,468, soprintfprints2147483648.Of course, the C standard does not define the behavior, so other things could happen, but this is a likely scenario for what did happen in the instance you observed.
Since
intis 32 bits in your C implementation, theint16_tvalueINT16_MINis automatically promoted tointfor the function call, so this passes anint, and%dexpects anint, so there is no mismatch, and the correct value is printed.Similarly, the other
printfcalls in the question have arguments that match the conversion specifications (given the particular definitions ofint16_tand such in your C implementation; they could mismatch in others), so their values are printed correctly.