user091ard:
Try this code (the only restriction is that your last argument has to be 0):
#include <stdarg.h>
int add(int num, ...)
{
int total = num;
int counter = 0;
int val = num;
va_list adding, count;
va_start (adding, num);
va_copy(count, adding);
while (val != 0)
{
val = va_arg(count, int);
++counter;
}
va_end(count);
for (int i = 0; i < counter - 1; ++i)
{
total += va_arg (adding, int);
}
va_end(adding);
return total;
}
void setup()
{
Serial.begin(9600);
}
void loop()
{
int buff = add(1, 2, 3, 4, 0);
Serial.println(buff);
delay(2000);
}
Or this solution (with INT_MAX):
#include <stdarg.h>
#include <limits.h>
int add(int num, ...)
{
int total = num;
int counter = 0;
int val = num;
va_list adding, count;
va_start (adding, num);
va_copy(count, adding);
while (val != INT_MAX)
{
val = va_arg(count, int);
++counter;
}
va_end(count);
for (int i = 0; i < counter - 1; ++i)
{
total += va_arg (adding, int);
}
va_end(adding);
return total;
}
void setup()
{
Serial.begin(9600);
}
void loop()
{
int buff = add(1, 2, 3, 4, 5, 1, INT_MAX);
Serial.println(buff);
delay(2000);
}
ok, thanks a lot. so using va_copy really doesn't work. It can't exit the arguments counting while loop by itself. while for a summing function, adding a zero to the end is okay, but it really doesn't work for me here, as I am not necessarily write a summing function. I will figure it out.