我正在閱讀的一本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然後看到重複的鏈接。這已經被問過。 –