我正在尝试编写一个使用具有可变数量参数的函数的程序。另一个任务是分别打印每个函数调用的所有参数。代码如下:-
#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;
}
该程序的输出如下:-
另一段代码是:-
#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;
}
输出如下:-
为什么会有这种差异?有什么帮助吗?