# foreach 與陣列

``````#include <stdio.h>

int main(void) {
int arr[] = {10, 20, 30, 40, 50};
int size = *(&arr + 1) - arr;
for(int i = 0; i < size; i++) {
printf("%d ", *(arr + i));
}

return 0;
}
``````

``````int arr[] = {10, 20, 30, 40, 50};
foreach(int *v, arr) {
printf("%d ", *v);
}
``````

``````int arr[] = {10, 20, 30, 40, 50};
for(int size = *(&arr + 1) - arr, i = 0; i < size; i++) {
int *v = arr + i;
printf("%d ", *v);
}
``````

``````#define foreach(item, arr)                                  \
for(int size = *(&arr + 1) - arr, i = 0; i < size; i++) \
item = (arr + i);
``````

``````int arr[] = {10, 20, 30, 40, 50};
for(int size = *(&arr + 1) - arr, i = 0, j = 0; i < size; i++, j = 0) {
for(int *v = arr + i; j < 1; j++)
printf("%d ", *v);
}
``````

``````#include <stdio.h>

#define foreach(item, arr)                                                \
for(int size = *(&arr + 1) - arr, i = 0, j = 0; i < size; i++, j = 0) \
for(item = arr + i; j < 1; j++)

int main(void) {
int arr[] = {10, 20, 30, 40, 50};
foreach(int *v, arr) {
printf("%d ", *v);
}

return 0;
}
``````

``````#include <stdio.h>

#define foreach(item, arr)                                                \
for(int size = *(&arr + 1) - arr, i = 0, j = 0; i < size; i++, j = 0) \
for(item = arr + i; j < 1; j++)

int main(void) {
int arr[] = {10, 20, 30, 40, 50};
foreach(int *v, arr) {
printf("%d ", *v);
if(*v > 30) {
break;
}
}

return 0;
}
``````

``````#include <stdio.h>

#define foreach(item, arr)                                                                  \
for(int size = *(&arr + 1) - arr, i = 0, loop = 1; loop && i < size; i++, loop = !loop) \
for(item = arr + i; loop; loop = !loop)

int main(void) {
int arr[] = {10, 20, 30, 40, 50, 60};
foreach(int *v, arr) {
printf("%d ", *v);
if(*v > 30) {
break;
}
}

return 0;
}
``````

``````#include <stdio.h>

#define foreach(item, arr)                                                                  \
for(int size = *(&arr + 1) - arr, i = 0, loop = 1; loop && i < size; i++, loop = !loop) \
for(item = arr + i; loop; loop = !loop)

typedef const char* String;

int main(void) {
String names[] = {"Justin", "Monica", "Irene"};
foreach(String *name, names) {
printf("%s ", *name);
}

return 0;
}
``````