【发布时间】:2020-02-18 01:07:20
【问题描述】:
当我运行以下代码时,有时它会成功退出,有时它会在highestNum等于255时进入无限循环。我知道这是因为当255递增并变为0时发生翻转。我明白为什么会这样正在发生,但我想就停止这种情况提出建议。我是否应该在最后放置一个 if 语句来检查 i 是否等于最大数,然后在最后中断?这似乎是一种糟糕的风格,如果我增加变量的大小,很容易忘记修复。
// delete all the files
for (unsigned char i = 0; i <= highestNum; i++){
rc = snprintf(formatString, sizeof(formatString), "x%u", i);
if (rc < 0){
perror("snprintf in delete");
}
rc = unlinkat(directoryFD, formatString, 0);
if (rc == 0){
printf("file unlinked\n");
}
}
【问题讨论】:
-
您需要为工作选择正确的变量。如果您知道您永远不会拥有
highestNum>= 255,那么当前的实现就可以了。但是,如果您可以拥有highestNum>= 255,那么您应该选择不同的类型。 -
使用
unsigned short而不是unsigned char代表i。
标签: c loops for-loop infinite-loop unsigned-char