The mystery of integer literals in C language

num_literal.c


#include <stdio.h>
#include <limits.h>

int main(void)
{
	int a;
	int b;
	int c;
	a = INT_MIN;
	b = -2147483648;
	c = -0x80000000;
	printf("(a == b): %d\n", (a == b));
	printf("(b == c): %d\n", (b == c));
	printf("(c == a): %d\n", (c == a));
	printf("(INT_MIN == -2147483648): %d\n",
			(INT_MIN == -2147483648));
	printf("(-2147483648 == -0x80000000): %d\n",
			(-2147483648 == -0x80000000));
	printf("(-0x80000000 == INT_MIN): %d\n",
			(-0x80000000 == INT_MIN));
	printf("sizeof(a): %zd\n", sizeof(a));
	printf("sizeof(b): %zd\n", sizeof(b));
	printf("sizeof(c): %zd\n", sizeof(c));
	printf("sizeof(INT_MIN): %zd\n", sizeof(INT_MIN));
	printf("sizeof(-2147483648): %zd\n", sizeof(-2147483648));
	printf("sizeof(-0x80000000): %zd\n", sizeof(-0x80000000));
	return 0;
}
$ clang -Wall -std=c11 num_literal.c -o num_literal && ./num_literal
(a == b): 1
(b == c): 1
(c == a): 1
(INT_MIN == -2147483648): 1
(-2147483648 == -0x80000000): 0
(-0x80000000 == INT_MIN): 1
sizeof(a): 4
sizeof(b): 4
sizeof(c): 4
sizeof(INT_MIN): 4
sizeof(-2147483648): 8
sizeof(-0x80000000): 4

(-2147483648 == -0x80000000) isn't just 1, it's the same no matter how you calculate it. Besides, only -2147483648 is size 8 and I feel sorry for being out of the group.

That's something I want to dig into, but C language masters already know why this happens. You don't need a commentary, right? I tell you, it's not a Clang bug. The result is the same with GCC.

Continue to Commentary.

Recommended Posts