Buy Now!!

Wednesday, September 10, 2014

Variable Argument Lists in C and C++

If you want to use a function which can take variable number of arguments, you can use variable argument list. For example you want to design a function which accepts any number of integers and returns the average of those integers.You don't know the number of arguments will be passed to the function. There are some library functions also which take variable number of arguments for example printf().

first of all you have to include  <stdarg.h> header file.
Then you have to define va_list type variable which will store the arguments. 

C language
C language
Let's try to understand with example:
#include<stdio.h>
#include<stdarg.h>


techshow irshad(char *arr, ...)
{
int num;
va_list ptr; /* create a new list ptr */
 

va_start(ptr,arr); /* attach ptr with arr */
printf("\n num=%d",arr); /* it will print 1st argument */
 

num = va_arg(ptr,int); /* fetch 2nd argument */
printf("\n num=%d",num);
 

num = va_arg(ptr,int); /* fetch 3rd argument */
printf("\n num=%d",num);


va_end ( arguments ); /* Cleans up the list */
}
int main()
{

printf("\n variable argument:");
techshow(10,20,30,40,50,0);
return 0;
}


/* output */

variable argument:
num=10
num=20
num=30 



You may also like :How to check whether particular bit is on or off in C language?