基本上这是一个将值写入 int 数组的简单函数。
我想给当前元素赋值,打印它和索引,然后自增索引到下一个元素。
然而,自增顺序的变化使得结果有所不同。
#include <stdio.h>
int buff[5];
int id;
void write ( )
{
int i;
i = id = 0;
printf("Iter 1\n");
while (i++ < 5) {
buff[id] = id;
printf("writes %d in buff[%d]\n", buff[id], id++);
}
i = id = 0;
printf("Iter 2\n");
while (i++ < 5) {
buff[id] = id;
printf("writes %d in buff[%d]\n", buff[id++], id);
}
}
int main ( )
{
write();
}
-------------
Output:
Iter 1
writes 0 in buff[0]
writes 0 in buff[1] // which should not be 0
writes 0 in buff[2] // which should not be 0
writes 0 in buff[3] // which should not be 0
writes 5 in buff[4] // which should not be 5
Iter 2
writes 0 in buff[0]
writes 1 in buff[1]
writes 2 in buff[2]
writes 3 in buff[3]
writes 4 in buff[4]
我知道在一个表达式中对同一个变量尝试多次自增操作可能会出现问题,但不知道为什么这里迭代1中的自增样式无法返回正确的id值。
感谢任何解释或建议。
最佳答案
您的代码有未定义的行为:
printf("writes %d in buff[%d]\n", buff[id], id++);
从检索 id
的值到修改它之间没有序列点,编译器可以自由地做任何它想做的事情。
正确的写法是:
printf("writes %d in buff[%d]\n", buff[id], id);
id++;
如果你编译时有警告,你应该得到类似于:
test.c:21:50: warning: operation on ‘id’ may be undefined [-Wsequence-point]
printf("writes %d in buff[%d]\n", buff[id++], id);
^
补充阅读:
关于c - C中自增返回0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22599941/