C Programming - Variable Number of Arguments - Discussion
Discussion Forum : Variable Number of Arguments - Find Output of Program (Q.No. 1)
1.
What will be the output of the program?
#include<stdio.h>
#include<stdarg.h>
void fun(char *msg, ...);
int main()
{
fun("IndiaBIX", 1, 4, 7, 11, 0);
return 0;
}
void fun(char *msg, ...)
{
va_list ptr;
int num;
va_start(ptr, msg);
num = va_arg(ptr, int);
num = va_arg(ptr, int);
printf("%d", num);
}
Discussion:
34 comments Page 4 of 4.
Manish roy said:
7 years ago
First of all va_start and va_arg are a macro defined in stdarg.h header file.
Va_list type is also defined in the stdarg.h,
Here ptr is va_list type variable.
Va_start macro and int parameter is used to initialize the va_list variable to an argument list.
Then we use va_arg macro and va_list variable to access each item in an argument list.
So num=va_arg(ptr,int); assigns integer value to num i.e.1.
Then the second statement num=va_arg(ptr,int);assigns 4 to num.
Then printf statement is given so 4 is printed and hence the output.
Va_list type is also defined in the stdarg.h,
Here ptr is va_list type variable.
Va_start macro and int parameter is used to initialize the va_list variable to an argument list.
Then we use va_arg macro and va_list variable to access each item in an argument list.
So num=va_arg(ptr,int); assigns integer value to num i.e.1.
Then the second statement num=va_arg(ptr,int);assigns 4 to num.
Then printf statement is given so 4 is printed and hence the output.
(1)
GUNA said:
6 years ago
Here, va_list, it is only focused to the defined values in the func arguments. As same here, here we have char msg also, that is totally differ on output. Main thing is on First call of var_arg it takes the first value of the argument and second time by default it moves on next value, that's what we got the output as 4.
Satapure abhishek said:
4 years ago
It is the ellipse program it is used to send multiple number of argument.
fun("indiabix",1,4,7,11,0);//fun call.
va_list ptr;//ptr is pointer of va_list;
num=va_arg(ptr,int);//num is int type ;
So it print 4;
fun("indiabix",1,4,7,11,0);//fun call.
va_list ptr;//ptr is pointer of va_list;
num=va_arg(ptr,int);//num is int type ;
So it print 4;
Enia said:
4 years ago
num = va_arg(ptr, int); // means num fetches the next element in the arguments that is of int type.
First time, it fetches the argument with 1 value. Neglecting the char * as it's not of type int
and second time, it fetches the argument with the 4 value.
First time, it fetches the argument with 1 value. Neglecting the char * as it's not of type int
and second time, it fetches the argument with the 4 value.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers