Reputation: 618
I am trying to write a program which uses function with variable number of arguments. An additional task is to print all the arguments of every function call separately. The code is as follows:-
#include<stdio.h>
#include<stdarg.h>
#include<string.h>
int mul(int x,...);
int main()
{
int a=1,b=2,c=3,d=4,x;
printf("The product of %d is :%d\n",a,mul(1,a));
printf("The product of %d, %d is :%d\n",a,b,mul(2,a,b));
printf("The product of %d, %d, %d is :%d\n",a,b,c,mul(3,a,b,c));
printf("The product of %d, %d, %d, %d is :%d\n",a,b,c,d,mul(4,a,b,c,d));
return 0;
}
int mul(int x,...)
{
int i,prod=1;
va_list arglist;
va_start(arglist, x);
for(i=0;i<x;i++)
{
prod*=va_arg(arglist,int);
}
printf("\n");
for(i=0;i<x;i++)
{
printf("The argument is %d\n",va_arg(arglist,int));
}
va_end(arglist);
return prod;
}
The output of this program is as follows:-
The other piece of code is:-
#include<stdio.h>
#include<stdarg.h>
#include<string.h>
int mul(int x,...);
int main()
{
int a=1,b=2,c=3,d=4,x;
printf("The product of %d is :%d\n",a,mul(1,a));
printf("The product of %d, %d is :%d\n",a,b,mul(2,a,b));
printf("The product of %d, %d, %d is :%d\n",a,b,c,mul(3,a,b,c));
printf("The product of %d, %d, %d, %d is :%d\n",a,b,c,d,mul(4,a,b,c,d));
return 0;
}
int mul(int x,...)
{
int i,prod=1;
va_list arglist;
va_start(arglist, x);
for(i=0;i<x;i++)
{
prod*=va_arg(arglist,int);
}
printf("\n");
va_end(arglist);
va_start(arglist,x);
for(i=0;i<x;i++)
{
printf("The argument is %d\n",va_arg(arglist,int));
}
va_end(arglist);
return prod;
}
The output is as follows:-
Why is this difference? Any help?
Upvotes: 1
Views: 2201
Reputation: 976
va_arg(va_list ap, type) retrieves next argument in the argument list.So in the first code you are consuming the arguments after one loop . Instead of 2nd code you can use the following code which prints argument and maintains multiplication in a single loop
int mul(int x,...)
{
int i,m,prod=1;
enter code here
va_list arglist;
enter code here
va_start(arglist, x);
for(i=0;i<x;i++)
{
m=va_arg(arglist,int);
prod*=m
printf("The argument is %d\n",m);
}
printf("\n");
return prod;
}
Upvotes: 0
Reputation: 838156
In the first example you are missing two lines:
va_end(arglist);
va_start(arglist,x);
This means that after doing the multiplication you are reading past the end of the parameters. The values that are displayed are whatever happened to be on the stack.
Upvotes: 2