[英]Why is the result of the 32-bit program different from the 64-bit one?
I was working on a assignment on integer byte level representation. 我正在进行整数字节级表示的赋值。 And I wrote a little program:
我写了一个小程序:
e1.c e1.c
int main(void) {
printf("%d\n", -2147483648 < 2147483647);
return 0;
}
When I compiled a 32-bit version of the executable file using the C89 standard, with the command gcc e1.c -m64 -std=c89 -g -O0 -o e1
, it worked as I expected: it printed 0
indicating that C compiler regarded the value 2147483648
as unsigned int
, thus it converts the rest of the expression to unsigned int
. 当我使用C89标准编译32位版本的可执行文件时,使用命令
gcc e1.c -m64 -std=c89 -g -O0 -o e1
,它按预期工作:它打印0
表示C编译器将值2147483648
视为unsigned int
,因此它将表达式的其余部分转换为unsigned int
。 But weirdly this relationship doesn't hold in the 64-bit version, which prints 1
. 但奇怪的是,这种关系并不适用于打印
1
的64位版本。
Can anyone explain that? 有谁能解释一下?
The type of an integer constant is the first of the corresponding list in which its value can be represented.
整数常量的类型是相应列表中可以表示其值的第一个。 Unsuffixed decimal:
int
,long int
,unsigned long int
;unsuffixed decimal:
int
,long int
,unsigned long int
; [...][...]
Thus, the type of the literal 2147483648
depends on the size of int
, long
, and unsigned long
, respectively. 因此,文字
2147483648
的类型分别取决于int
, long
和unsigned long
的大小。 Let's assume int
is 32 bits, as it is on many platforms (and is likely the case on your platforms). 假设
int
是32位,因为它在许多平台上(在您的平台上可能就是这种情况)。
On a 32-bit platform, it's common for long
to be 32 bits. 在32位平台上,
long
32位是long
常见的。 Thus, the type of 2147483648
would be unsigned long
. 因此,
2147483648
的类型将是unsigned long
。
On a 64-bit platform, it's common for long
to be 64 bits (though some platforms, like MSVC, will still use 32 bits for long
). 在64位平台上,通常
long
64位(尽管某些平台,如MSVC,仍然会long
使用32位)。 Thus, the type of 2147483648
would be long
. 因此,
2147483648
的类型会很long
。
This leads to the discrepancy you see. 这会导致你看到的差异。 In one case, you're negating an
unsigned long
, and in the other case, you're negating a long
. 在一种情况下,你是在否定一个
unsigned long
,而在另一种情况下,你是在否定一个long
。
On a 32-bit platform, -2147483648
evaluates to 2147483648
(using the unsigned long
type). 在32位平台上,
-2147483648
计算结果为2147483648
(使用unsigned long
类型)。 Thus the resulting comparison is 2147483648 < 2147483647
, which evaluates to 0
. 因此,得到的比较是
2147483648 < 2147483647
,其评估为0
。
On a 64-bit platform, -2147483648
evaluates to -2147483648
(using the long
type). 在64位平台上,
-2147483648
计算结果为-2147483648
(使用long
类型)。 Thus the resulting comparison is -2147483648 < 2147483647
, which evaluates to 1
. 因此,得到的比较是
-2147483648 < 2147483647
,其评估为1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.