c - for (unsigned char i = 0; i<=0xff; i++) 产生无限循环

标签 c loops unsigned-char

为什么下面的 C 代码会陷入死循环?

for(unsigned char i = 0; i <= 0xff; i++){}

结果相同:

for(unsigned char i = 0; i <= 0xff; ++i){}

我必须以哪种方式修改代码,使其按预期工作(不使用 intunsigned int 数据类型)?

最佳答案

如果你真的需要使用unsigned char那么你可以使用

unsigned char i = 0;
do {
    // ... 
} while(++i);

当对unsigned 整数的算术运算超出其限制时,行为是明确定义的。所以这个解决方案将处理 256 个值(对于 8 位 unsigned char)。

关于c - for (unsigned char i = 0; i<=0xff; i++) 产生无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45493449/

相关文章:

c - 在循环中生成一个新数组

c++ - 将文件中的值赋值给 unsigned char 变量的奇怪行为

c++ - 如何使用 setfill 和 setw 在字符串变量中存储十六进制值

c++ - MPI_Send/Recv C++ std::string 段错误

c - 输入从不存在的文件重定向到 fopen()

r - 在 R 如何将具有动态名称的数据框复制到静态命名的数据框

python - 我是否在这个生成器函数中过度使用了变量?

c++ - 将字符串转换为 unsigned char []

编码 : Can anyone explain me this why there are different outputs when comparing Least significant bits of two numbers?

枚举成员可以是 ANSI-C 中数组的大小吗?