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"

2
  • 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)? Commented Oct 28, 2015 at 5:50
  • Suggest edit/compile/runit both ways, see if there is any difference Commented Oct 29, 2015 at 16:25

3 Answers 3

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*.

Sign up to request clarification or add additional context in comments.

2 Comments

you're right, use point is more saving memory, but if i change "int *v" to "int v" and "(array) + count" to "array[count", it's more convenient.
@nwaicaethi, you could do that.
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];

1 Comment

@chux my mistake and thanx
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.

1 Comment

NMDV There is no function call in the post so why "Arrays decay to pointers when you pass them to a function".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.