It works for a while, returns 0 instead -1 from the va_arg macro, returns other garbage values and keeps looping …
Results:
a: 2
total: 2
a: 3
total: 5
a: 4
total: 9
a: 0
total: 9
a: 0
total: 9
a: 0
total: 9
a: 97
total: 106
a: 32
total: 138
a: 116
total: 254
…etc
#include <stdio.h>
//#include <stdargs.h>
int Add(uint8_t a, ...)
{
//This one handles 4 arguments in total.
int total=0;
//Declare a va_list macro and initialize it with va_start
va_list l_Arg;
va_start(l_Arg, a);
while( a != -1 ) {
Serial.print("a: ");
Serial.println(a, DEC);
total += a;
Serial.print("total: ");
Serial.println(total);
a = va_arg(l_Arg, int); // using '...' promotes uint8_t to int
}
va_end(l_Arg);
return total;
}
void setup ()
{
Serial.begin(9600);
Serial.println(Add(2,3,4));
}
void loop() {
delay(1000);
}
I found another example of code that seems more logical - the first argument indicates the number of subsequent arguments. It produces the desired result.