【问题标题】:does the incrementation of unsigned int cause undefined behavior when the variable reach the Max当变量达到最大值时,unsigned int 的增量是否会导致未定义的行为
【发布时间】:2013-12-13 15:30:10
【问题描述】:

我的代码中有一个计数器,当它达到无符号整数最大值时,我希望我的计数器回到 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

}

【问题讨论】:

    标签: c++ c int


    【解决方案1】:
    a= a+1; //is it allowed to increment "a" when "a" reach the Max ? 
    

    是的,无符号整数永远不会溢出(这是 C 术语)。所以UINT_MAX + 1 是定义的行为并被评估为0

    (C99, 6.2.5p9) “涉及无符号操作数的计算永远不会溢出,因为无法由生成的无符号整数类型表示的结果会以比可以表示的最大值大一的数字为模减少按结果类型。”

    【讨论】:

      【解决方案2】:

      无符号算术被定义为模数,模数为2^BITS == MAX+1。所以增加最大值被定义为零。

      另一方面,有符号溢出确实会产生未定义的行为。

      在 C 和 C++ 中都是如此。

      【讨论】:

      • 您能否澄清这是否也意味着如果减法的结果为负,无符号算术会“向后”环绕?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      • 2015-01-16
      • 2016-02-17
      • 1970-01-01
      • 2022-08-24
      • 2017-04-08
      • 1970-01-01
      相关资源
      最近更新 更多