gpt4 book ai didi

c++ - 当变量达到最大值时,unsigned int 的递增会导致未定义的行为吗

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:57:19 25 4
gpt4 key购买 nike

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

}

最佳答案

a= a+1; //is it allowed to increment "a" when "a" reach the Max ? 

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

(C99, 6.2.5p9) "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."

关于c++ - 当变量达到最大值时,unsigned int 的递增会导致未定义的行为吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20570125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com