对此有一个窥视。编译器抱怨说我有一个整数溢出,但是当我查看C89标准的整数提升规则以及该表达式中的值时,似乎没有溢出。C积分溢出?
[email protected]:~$ cat test.c
#include <stdio.h>
#include <inttypes.h>
const uint32_t value =
(0x7F-0x00 + 1) * (256 + 256*256 + 256*256*256) +
(0xDF-0xC2 + 1) * (256 + 256*256 + 256*256*256);
int
main(void)
{
printf("value = %"PRIu32"\n", value);
return 0;
}
[email protected]:~$ gcc -std=c89 -pedantic -Wall -Wextra test.c
test.c:5: warning: integer overflow in expression
test.c:6: warning: integer overflow in expression
test.c:6: warning: overflow in constant expression
[email protected]:~$ ./a.out
value = 2661195264
[email protected]:~$
此外,谷歌确认2661195264的答案是该表达的正确值! (See this link)
那么,程序如何在有整数溢出时产生正确的值?更重要的是,该表达式中的整数溢出是如何开始的?
也许它使用signed int而不是unsigned,那么尽管计算了正确的无符号值,但在签名操作中会发生溢出。 – Nobody