Showing entries with tag "foreach".

Found 1 entries

C++: Foreach over an array

If you have an array of elements that you want to iterate over you can do this:

int dpins[] = { 2, 4, 7, 12 };

for (int i = 0; i < (sizeof(dpins) / sizeof(dpins[0])); i++) {
    int pin  = dpins[i];
    int pval = digitalRead(pin);

    printf("%i = %i", pin, pval);
}

There is also a newer syntax adopted in C++11 (and supported by Arduino) that is more readable:

int dpins[] = { 2, 4, 7, 12 };

for (int pin : dpins) {
    int pval = digitalRead(pin);

    printf("%i = %i", pin, pval);
}
Leave A Reply