c - C中自增返回0?

标签 c

基本上这是一个将值写入 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/

相关文章:

c++ - 使用硬件内存保护在64位硬件上进行数组范围检查

c++ - 打印__float128,而不使用quadmath_snprintf

c - 为什么 scanf 没有在我期望的时候终止

c - 如何将文件扫描到链表中?

java - 优化 : Is the order of cases in a switch statement important?

c++ - 如何通过传递参数从 C++ 调用 R 函数

c - 泰勒级数计算余弦(余弦(90)的输出为-0.000)

c - 数组的行为

C - 如何使用变量作为 SQL 查询的一部分?

在 Objective-C 中检查对象的大小