I was reading about variable length arguments for functions in the C programming language and I thought, “hey, will this thing work on an Arduino?”.. well, it turns out that yes, it’s working great!
But, what are functions with a variable length? Well, the standard C printf function is a good example (not available on Arduino of course). You can call it with how many arguments you want, for example:
printf("%d", 5); printf("%d %d", 5, 7);
So, how can we make this with the Arduino? Here is an example, using the same example from here, just ported into Arduino code:
#include <stdarg.h> #include <stdio.h> /* this function will take the number of values to average followed by all of the numbers to average */ float average ( int num, ... ) { va_list arguments; float sum = 0; /* Initializing arguments to store all values after num */ va_start ( arguments, num ); /* Sum all the inputs; we still rely on the function caller to tell us how * many there are */ for ( int x = 0; x < num; x++ ) { sum += va_arg ( arguments, double ); } va_end ( arguments ); // Cleans up the list return sum / num; } void setup() { Serial.begin(9600); } void loop() { float avg = average( 3, 12.2, 22.3, 4.5 ); Serial.println(avg); avg = average( 5, 3.3, 2.2, 1.1, 5.5, 3.3 ); Serial.println(avg); delay(1000); }