Variable Length of Arguments in C - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Variable Length of Arguments in C

Share This
If you are familiar with method overloading, you know that more than one function can be defined by the same name (ex. in Java, C++ etc.). But C language does not support function overloading. Hence two functions can not be defined by the same name.

Now, if you want to pass one or more arguments to a function and the function should work with a different number of arguments. You have to use the technique of variable length of arguments.

In the following program, we are defining a function to calculate the average of numbers, where the function will receive one or more than one arguments.

The following example shows that the function, average() is defined in such a way that the function can receive any number of arguments and perform the specified operation like average of integer values.


#include <stdio.h> #include <stdarg.h> float average(int count, ...); int main() { // the following fuction call sends 3 as number of arguments and the values (15, 20 and 25) float res = average(3, 15, 20, 25); printf("Average is :%f\n", res); // the following fuction call sends 2 as number of arguments and the values (15 and 20) res = average(2, 15, 20); printf("Average is :%f\n", res); // the following fuction call sends 5 as number of arguments and the values (15, 10, 20, 30 and 50) res = average(5, 15, 10, 20, 30, 50); printf("Average is :%f\n", res); return 0; } float average(int count, ...) { va_list ap; int j; int sum = 0; va_start(ap, count); for (j = 0; j < count; j++) { sum += va_arg(ap, int); } va_end(ap); printf("Sum is : %d\n", sum); return ((float)sum / count); }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.