My problem is: I want to call the method, but I don't know at compile-time which arguments I want to pass.Is there some way by which I can create the va_list during run time and pass it to the fucntion.

Eg Code:
total(4, 1,2,3,4) ;//Where 4 is the number of arguments and 1,2,3,4 is my va_list;

int total( int numargs, ... )
{

int sum = 0;
int i ;

int arg;


va_list listpointer;
va_start(listpointer,numargs);
//printf(" The numarg value is %d\n",numargs);


 while(arg!= 0)
 {
  arg = va_arg(listpointer,int);

  //printf(" The arg returned %d",arg);

  sum += arg;

 }

va_end(listpointer);

printf("Total Purchase amount = %d\n", sum);
return sum;

}

the above works fine and gives me a correct output.

But, as you can see I am defining the va_list during compile time only but not in run time.Is there an elegant way to accept the arguments in runtime and pass it to the total function at runtime and it would add up and show the result.

Thanks
Sumit

Edited 6 Years Ago by Nick Evan: Added code-tags

I don't understand what you are asking. That function will sum up however many integers you want to pass to it as long as the last parameter is 0 so that the function knows when to stop.

You might want to recode that while loop because the first time through the value of arg is undefined.

while( (arg = va_arg(listpointer,int)) != 0)
{
    sum += arg;
}

int main()
{
    // Note that the lastg parameter is 0
    // which tells total() when to stop summing.
    // The first parameter is just ignored by total()
    int x = total(0,1,2,3,4,5,6,7,9,10,11,12,0);
}

Edited 6 Years Ago by Ancient Dragon: n/a

Comments
Good Reply

Well, let me explain by taking your code example.

In your code you have written this line.

int x = total(0,1,2,3,4,5,6,7,9,10,11,12,0);

here y0u have given the numbers which you liked.

My question is: Instead of you giving the numbers is there any way to accept those numbers at runtime from the user and pass the same to tal function.

Well this is the output I am expecting on running:

OUTPUT
======
Enter the numbers you want to add separated by comma:
1,2,3,4

The Total is 10

Of course there is

int a,b,c,d,e,f,g,h;
total(a,b,c,d,e,f,g,h,0);

Or you can just pass an array of integers, which doesn't require va_args at all.

const int MAX = 15;
int array[MAX];
total(array, MAX);
Comments
Ah an array, so simple and clear :)
Happiness, eh? What does that mean?
This article has been dead for over six months. Start a new discussion instead.