Functions with variable number of arguments

So far have seen that function definition matches with function declaration. Sometimes it is necessary or convenient to design a function that can be called with either a different number or type of arguments. Library functions like printf and scanf

printf (“%d%f%s%c”, x, y, msg, ch);
printf (“%s %c”, str, *cptr);

work this way. This task can be achieved by making the function to accept a pointer to an array. Another way to accomplish this task is to write function that can take any number of arguments.

For performing this task, C has a header file by name stdarg.h that contains library functions to accept variable number of arguments. To use a function with variable number of arguments, the function shown in table are found very useful.

some useful functions for implementing a function for variable number of arguments

img

The declaring the function must have the following property:

  • • Must have at least one fixed argument
  • • Fixed arguments(s) listed first, must have data type
  • • Use ellipses after the last fixed argument to denote start of variable arguments
  • • Must design so that function can determine the number and type of the variable arguments

For example:

int max (int count, ….);

where max is the name of the function, count is fixed argument, the ellipses (. . .) indicate the variable number of arguments.

Accessing the arguments

Declare a local argument pointer of type va_list

Va_list varptr;

Use function va_start to position to first variable arg

va_start (varptr, startarg);


where varptr is the previously – defined argument pointer and startarg is the argument in the function declaration that precedes the first variable arg you went (usually the last fixed arg)

Use function va_arg, specifying data type, for each variable argument accessed

va_arg (varptr, datatype);

datatype is any valid data type, including user_defined structure, union and enumeration types.

Use function va_end when finished processing argments

va_end (varptr);



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext