我前几天正在阅读C标准,并注意到与有符号整数溢出(未定义)不同,无符号整数溢出是明确定义的.我已经看到它在很多代码中用于最大化等等但是考虑到有关溢出的voodo,这被认为是很好的编程习惯吗?无论如何不安全吗?我知道许多像Python这样的现代语言都不支持它 - 相反,它们继续扩展大数字的大小.
我正在研究一个更新20年代码的项目,其中许多问题都与整数溢出有关.我想确保我正确测试溢出,所以我写了一个测试程序.它的输出让我感到沮丧.这里是:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <limits.h>
int main (void) {
size_t largerNum,Num;
largerNum = 12;
Num = UINT_MAX;
printf("largerNum = %u\nNum = %u\nNum + 1 = %u\n", largerNum , Num, Num + 1);
largerNum = Num + 1;
printf("largerNum now = %u\n", largerNum);
if(largerNum < Num ){
printf("largerNum overflowed to %u\n", largerNum);
}
else {
printf("largerNum did not overflow: %u\n", largerNum);
}
printf("Is (0 < UINT_MAX)?\n");
(0 < UINT_MAX)?printf("YES\n"):printf("NO\n");
printf("Is (largerNum < Num)?\n");
(largerNum < Num)?printf("YES\n"):printf("NO\n");
return …Run Code Online (Sandbox Code Playgroud) 试图了解标准中的语法:
6.3.1.3有符号和无符号整数
- 将具有整数类型的值转换为_Bool以外的其他整数类型时,如果该值可以用新类型表示,则该值不变。
- 否则,如果新类型是无符号的,则通过重复添加或减去比新类型可表示的最大值多一个值来转换值,直到该值在新类型的范围内为止。
- Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
Note section 2, which means that casting int to unsigned int is performed by adding UINT_MAX + 1 to the value in the int.
Which is discussed for example in those two discussions:
Can a C compiler change bit representation when casting signed to unsigned? …