Variable Length of Arguments in C - BunksAllowed

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

Random Posts

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. 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.

#include <stdio.h> #include <stdarg.h> float average(int count, ...); int main() { float res = average(3, 15, 20, 25); printf("Average is :%f\n", res); res = average(2, 15, 20); printf("Average is :%f\n", res); 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