为什么在 foreach 宏中使用“(array) + count”?

Why use "(array) + count" in foreach macro?

我从 here

获取 foreach 宏
#define foreach(item, array) \
    for(int keep = 1, \
            count = 0,\
            size = sizeof (array) / sizeof *(array); \
        keep && count != size; \
        keep = !keep, count++) \
      for(item = (array) + count; keep; keep = !keep)

我不明白“(array) + count”,它等于“&array[count]”,但为什么不使用"array[count]"而不是“(array) + count”

它们是等价的,你使用哪个完全取决于程序员的语义风格。

当您将数组传递给函数时,数组会衰减为指针,准确地说是指向第一个数组元素的指针。因此,您可以同时使用两者。

array+count&array[count]count+array没有区别。

只是这些都是地址,所以您不能像以前那样将它们分配给整数值:

int item=array+count;

但是指向整数指针:

int* item=array+count; or int* item= &array[count];

but why not use "array[count]" instead of "(array) + count"

来自 the linked post,

foreach(int *v, values) {
    printf("value: %d\n", *v);
}

在宏中,itemint* 类型,并且 array[count] 属于 int.

类型

因此您不能使用:

item = array[count];

但是你可以使用

item = (array) + count;

因为 (array) + count 的计算结果为 int*