使用 size_t 运算符的数组的增量值

The incrementer values for an array using a size_t operator

在下面的一段代码中:

#include <stdio.h>
#include <stddef.h>

void main ()
{
    int n[5] = {1,2,3,4,5};
    
    printf("%s%13s\n","element","value");
    for (size_t i = 0; i<5; ++i)
    {
           printf("%7d%13u\n", i, n[i]);
        }
    
}

输出是:

element        value
  0            1
  1            2
  2            3
  3            4
  4            5

我不明白的是 i 是如何预递增的,给出从 0 到 4 的值。

我认为应该是 1 到 4,因为它不会通过条件。

这背后的原因是什么?

What I don't understand is how i which is pre-incremented

不是,in[i]printf 循环中是完全独立的。

  • i还是从0增加到4
  • n[i] 则具有从 1 到 5 的对应值。索引 i 仍在 [0,4] 范围内。

顺便说一下,你应该使用 %zu 作为 size_t 类型。

for (size_t i = 0; i < 5; ++i)
{
    printf("%7zu%13d\n", i, n[i]);
}

在循环定义的第三部分中,计数器 i 仅在 ++i; 内 pre-incremented。这是一个完整的陈述,其中 pre 或 post 增量是无关紧要的。
i 的可观察行为与增量无关,因为所有输出都在单独的循环体中完成。

正如 Unholy sheep 在评论中提到的:

the third part of the for loop statement (the iteration expression) is always executed after an iteration finishes

进一步阐明评论和其他答案的观点

the third part of the for loop statement (the iteration expression) is always executed after an iteration finishes

该循环的手动展开将是

#include <stdio.h>
#include <stddef.h>

void main ()
{
    int n[5] = {1,2,3,4,5};
    
    printf("%s%13s\n","element","value");
    size_t i = 0;
    printf("%7d%13u\n", i, n[i]);
    ++i;
    printf("%7d%13u\n", i, n[i]);
    ++i;
    printf("%7d%13u\n", i, n[i]);
    ++i;
    printf("%7d%13u\n", i, n[i]);
    ++i;
    printf("%7d%13u\n", i, n[i]);
    ++i;
}