11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C言語の整数リテラルの謎

Last updated at Posted at 2015-03-16
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)だけなんで1じゃないんだ、どう計算しても同じだろう。それに-2147483648だけがサイズ8って仲間はずれでかわいそうじゃないか。

って、突っ込みたいところですが、C言語マスターの皆さんはどうしてこうなるかはもうおわかりですよね。解説なんていらないっしょ?言っておきますけど、Clangのバグじゃないですよ。GCCでも結果は同じです。

解説編へ続く。

11
10
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?