Showing entries with tag "C".

Found 2 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

C/C++: Appending to a string with sprintf()

I'm a big fan of sprintf() and use it in a lot of projects. Often I will want to append to a string instead of creating a new one. This solution will create an "end of string" function named eos() that returns a pointer to the end of a given string. If you feed that to sprintf() it will effectively append to the existing string.

char *eos(char str[]) {
    return (str) + strlen(str);
}

int main(int argc, char *argv[]) {
    char tmp_str[50] = "";

    sprintf(eos(tmp_str), "Weird");
    sprintf(eos(tmp_str), " Al");
    sprintf(eos(tmp_str), " Yankovic");
}
Leave A Reply