美好的一天,同事们!
我需要获取从0到255的连续数字的循环序列.使用无符号字符溢出是否合法:
unsigned char test_char = 0;
while (true) {
std::cout << test_char++ << " ";
}
Run Code Online (Sandbox Code Playgroud)
或者更安全地使用此代码:
int test_int = 0;
while (true) {
std::cout << test_int++ % 256 << " ";
}
Run Code Online (Sandbox Code Playgroud)
当然,在实际代码中会有合理的条件而不是while(true).
3.9.1/4"无符号整数,声明无符号整数,应遵守算术模2n的定律,其中n是整数特定大小的值表示中的位数"
"这意味着无符号算术不会溢出,因为无法通过生成的无符号整数类型表示的结果以模数减少,该数值大于可由结果无符号整数类型表示的最大值"
所以,是的,它是合法的.第二种形式是首选,因为它更具可读性.