Variable Length of Arguments in C - BunksAllowed

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

Community

demo-image

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#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);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX


Happy Exploring!

Comment Using!!

No comments:

Post a Comment

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