当变量达到Max时,unsigned int的增量会导致未定义的行为

Ani*_*ack 4 c c++ int

我的代码中有一个计数器,当计数器达到unsigned int max值时,我希望我的计数器返回0.我测试了一个小代码,它的工作原理,但我不知道它是否是一个未定义的行为

#include <stdio.h>
#include <string.h>

main()
{
  unsigned int a = 0;
  a= ~a; // Max value of unsigned int 
  printf("%u \n", a );
  a= a+1; //is it allowed to increment "a" when "a" reach the Max ? 
  printf("%u \n", a ); // display 0

}
Run Code Online (Sandbox Code Playgroud)

oua*_*uah 9

a= a+1; //is it allowed to increment "a" when "a" reach the Max ? 
Run Code Online (Sandbox Code Playgroud)

是的,无符号整数从不溢出(这是C术语).所以UINT_MAX + 1定义了行为并进行了评估0.

(C99,6.2.5p9)"涉及无符号操作数的计算永远不会溢出,因为无法用结果无符号整数类型表示的结果是以一个大于可由结果表示的最大值的数量的模数减少的.类型."


Mik*_*our 9

无符号算术被定义为模块化的,模数为2^BITS == MAX+1.因此,增加最大值定义为零.

另一方面,有符号溢出确实给出了未定义的行为.

C和C++都是这种情况.