'Is this a safe / correct implementation of a variadic list argument used to simplify setting "pinMode"?
Code (C++):
I'm new to C++ so I'm not sure if this is safe:
#include <Arduino.h>
void pin_mode(uint8_t pins[], uint8_t mode) {
const int length = *(&pins + 1) - pins;
for (size_t i = 0; (signed)i < length; i++) {
pinMode(pins[i], mode);
}
}
I have multiple pins that have the same pin setting, I'd like to set their values on one line instead of having 12 + lines that call the same function.
Usage:
pin_mode([PIN_1, PIN_2, PIN_3, PIN_4], OUTPUT);
Is this a safe / correct implementation?
Solution 1:[1]
If I were doing this, I'd pass the array by reference, so the compiler would compute its size for me:
#include <Arduino.h>
template <size_t N>
void pin_mode(uint8_t (&pins)[N], uint8_t mode) {
for (size_t i = 0; i < N; i++) {
pinMode(pins[i], mode);
}
}
Of course, with this you're free to use a range-based for loop if you prefer.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jerry Coffin |
