我的代码中有一个计数器,当计数器达到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)
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)"涉及无符号操作数的计算永远不会溢出,因为无法用结果无符号整数类型表示的结果是以一个大于可由结果表示的最大值的数量的模数减少的.类型."
| 归档时间: |
|
| 查看次数: |
4379 次 |
| 最近记录: |