1

I get foreach macro from here

#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)

I don't understand "(array) + count", it's equal "&array[count]", but why not use "array[count]" instead of "(array) + count"

Community
  • 1
  • 1
nwaicaethi
  • 175
  • 3
  • 10
  • Do you mean "why not use `array[count]`" (as written) or "why not use `@array[count]`" (as per your comment on what `(array) + count` is equal to)? – rici Oct 28 '15 at 05:50
  • Suggest edit/compile/runit both ways, see if there is any difference – user3629249 Oct 29 '15 at 16:25

3 Answers3

4

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

From the linked post,

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

In the macro, item is of type int* and array[count] is of type int.

Hence you cannot use:

item = array[count];

But you can use

item = (array) + count;

since (array) + count evaluates to an int*.

Community
  • 1
  • 1
R Sahu
  • 204,454
  • 14
  • 159
  • 270
3

There is no difference in array+count and &array[count] or count+array.

Its just these are both addresses so you cant assign them to an integer value as you did previously:

int item=array+count;

But to an integer pointer:

int* item=array+count; or int* item= &array[count];
wrangler
  • 3,454
  • 1
  • 19
  • 28
1

They are equivalent, which one you use is purely up to semantic style of the programmer.

Arrays decay to pointers when you pass them to a function, pointers to the first array element to be exact. Thusly, you can use both.

Magisch
  • 7,312
  • 9
  • 36
  • 52