我正在阅读的一本c编程书(c编程,现代方法第2版)说,当在无符号整数运算期间发生溢出时,结果是定义“。为什么整数在溢出时有不同的行为
这里是一个小的代码示例
#include <stdio.h>
int main()
{
unsigned short int x = 65535; // The unsigned short int is at the maximum possible range
x += 1; // If I add one to it will overflow.
printf("%u", x); // the output will be zero or one if decide to add plus one again to x
return 0;
}
他接着说,“为有符号整数,这些整数的行为没有定义”。这意味着程序可以打印出错误的结果,也可能导致程序崩溃。
这是为什么?
你问为什么有符号整数溢出的行为是未定义的,(*因为语言规范说它是*),或为什么规范定义无符号整数溢出但声明有符号整数溢出未定义(* [签署的值](http://stackoverflow.com/questions/18195715/why-is-unsigned-integer-overflow-defined-behavior-but-signed-integer-overflow-is)*)?另外,请不要使用'%d'打印无符号值 - 出于某种原因,'%u'存在。 –
@IskarJarak“为什么规范定义了无符号整数溢出,但声明了有符号整数溢出未定义?”你的这句话是我问的。 –
@LuisAverhoff然后看到重复的链接。这已经被问过。 –