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;
//printf(" The numarg value is %d\n",numargs);

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

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

  sum += arg;



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.


Recommended Answers

All 3 Replies

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);
commented: Good Reply +0

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:

Enter the numbers you want to add separated by comma:

The Total is 10

Of course there is

int a,b,c,d,e,f,g,h;

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);
commented: Happiness, eh? What does that mean? +4
commented: Ah an array, so simple and clear :) +19
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.