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);
}


Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 18.221.187.121
To prevent spam please submit by clicking the kitten: