C: Variable Argument List Access

Here, I explained how we can utilize the operator ellipsis (…) to pass variable number of arguments to a function. I have utilised there the concept of pointers to access the variable arguments. The standard C Library provides support to access these arguments. Use for this support
All you need is to know the last argument before the ellipsis operator(At least one argument is must to use variable arguments), let’s call it larg


    fun(type var1,type var2,...)

is a function, then larg corresponds to var2

Now we need to declare the list using va_list

    va_list al

now initialize it using va_start


Now to access each argument, we must know the expected type of the argument

     type var_name = va_arg(al,type);

When we have accessed all the variable arguments, we need to clean up


Using standard library, we can easily access the variable arguments

Take a simple example

#include <stdarg.h>
int print(int num_count,...)
/*num_count contains the number of integers passed*/
  int i;
  va_list al;
     int val=va_arg(al,int);
     printf("%d ",val);


int print_str(const char *str,...)
/*str has the number of strings passed*/
  int i;
  va_list al;
  int num_count=atoi(str);
  int *num=&num_count;
     char *str=va_arg(al,char *);
     printf("%s ",str);


int main()


2 3 4 Hi All !!!



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s