PoiNtEr->: Variable Arguments Handling in C

                             Difference between a dream and an aim. A dream requires soundless sleep, whereas an aim requires sleepless efforts.

Search This Blog

Monday, September 3, 2012

Variable Arguments Handling in C



There are cases where a function needs to accept varying numbers of arguments of varying type. For this we can use the macros defined in the header file stdarg.h. In this header file (stdarg.h) there macros defined that can be used to access the arguments of a list of unnamed (arguments with no corresponding parameter declarations) arguments.
There is one type described in stdarg.h:
  • va_list Holds the information about variable arguments.
  • The typedef va_list is used by the macros.
The following macros are defined:
  • va_start() Initializes the list of variable arguments.
  • va_arg() Expands the next argument in the parameter list of the function with a type. Note: the used va_list must be initialized with va_start.
  • va_end() Allows a function with variable arguments (which used the va_start macro) to return. Note: the used va_list may no longer be used after a va_end call.
To use a varying number of arguments (unamed) in a function we have to add a comma and three dots after its regular named parameters:
Usage: return_type function_name( regular_declarations, …)
Example: void my_print(int my_args, …)
Take a look at a source code example:

#include<stdio.h>
#include<stdarg.h>

void printargument(int num_args, ...)
{
    va_list arg_list;
    int my_arg;

    va_start(arg_list, num_args);

    //Print until zero
    for (my_arg = num_args; my_arg != 0; my_arg = va_arg(arg_list, int))
        printf("%d\n", my_arg);

    va_end(arg_list);
}

int main(void)
{
    printargument(1,20,5,35);
    return 0;
}
output:


 After Getting a zero argument function quits.So if you are thinking of using zero as a normal argument then its not possible to do that ,according to my knowledge.And my question is  who uses a zero as a argument ??If you do then leave comment below->>>

No comments:

Post a Comment