简体   繁体   English

UINT_MAX + 1等于什么?

[英]UINT_MAX + 1 equals what?

What is the defined behavior in C for UINT_MAX + 1u ? 对于UINT_MAX + 1u ,C中定义的行为是什么? How safe is to assume it is zero? 假设它为零是多么安全?

From the standard (C11, 6.2.5/9, emphasis mine): 从标准(C11,6.2.5 / 9,强调我的):

[...] A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type . [...]涉及无符号操作数的计算永远不会溢出,因为无法由结果无符号整数类型表示的结果以比模式结果类型可以表示的最大值大1的数量减少

If UINT_MAX is 10 : 如果UINT_MAX10

(10 + 1) % (10 + 1) == 0

So, yes, it's safe to assume it's zero. 所以,是的,假设它为零是安全的。

It's worth emphasizing that while unsigned behavior is well-defined, signed integer overflow isn't: 值得强调的是,虽然无符号行为是明确定义的,但有符号整数溢出不是:

In the C programming language, signed integer overflow causes undefined behavior, while unsigned integer overflow causes the number to be reduced modulo a power of two 在C编程语言中,带符号的整数溢出会导致未定义的行为,而无符号整数溢出会导致数量减少,模数为2

A very good paper on the subject: 关于这个主题的一篇非常好的论文:

EXAMPLES OF C/C++ INTEGER OPERATIONS AND THEIR RESULTS C / C ++整数运算的例子及其结果

Expression             Result
----------             ------
UINT_MAX+1             0
LONG_MAX+1             undefined
INT_MAX+1              undefined
SHRT_MAX+1             SHRT_MAX+1 if INT_MAX>SHRT_MAX, otherwise undefined
char c = CHAR_MAX; c++ varies
-INT_MIN               undefined
(char)INT_MAX          commonly -1
1<<-1                  undefined
1<<0                   1
1<<31                  commonly INT_MIN in ANSI C and C++98; undefined in C99 and C++11
1<<32                  undefined
1/0                    undefined
INT_MIN%-1             undefined in C11, otherwise undefined in practice

It's safe. 它是安全的。 The C standard guarantees that unsigned integer overflow wrap-around results in zero. C标准保证无符号整数溢出环绕结果为零。

Should be safe: 应该是安全的:

Wiki on unsigned overflow Wiki上无符号溢出

Note the unsigned int overflow is well defined. 注意unsigned int overflow定义良好。

Also, here's a whole question on this. 此外,这是一个完整的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM