in Programming in C
1,070 views
2 votes
2 votes
#include <stdio.h>
#include <stdarg.h>
int fun(int n, ...)
{
    int i, j = 1, val = 0;
    va_list p;
    va_start(p, n);
    for (; j < n; ++j)
    {
        i = va_arg(p, int);
        val += i;
    }
    va_end(p);
    return val;
}
int main()
{
    printf("%d\n", fun(4, 1, 2, 3));
    return 0;
}

will you explain the output for the program?

in Programming in C
1.1k views

1 Answer

1 vote
1 vote
Best answer

This program is performing the addition of the numbers which you passed as an argument to the function.

We know how to pass fixed number of arguments to the function for eg,funct(x,y)...in this function we have fixed number of arguments.

We can pass infinite numbers of arguments to the function and the same we have to declare a function in a particular syntax.

For example in this ques you have declare a function like this  fun(int n, ...),in this function int n specifies the number of arguments you want to pass to function 'fun' followed by three dots(...) this is the syntax .Now va_list variable has to be created in the function definition itself(like this va_list p; and this variable p has to be initialized using the two macros int and  va_start . va_list and va_arg macros are used to access the elements of the argument list.....va_list contains all the elements you have passed as an argument to a function.

Now execute the for loop.In for loop first statement is: i = va_arg(p, int); here va_arg(p, int) takes an element from the argument list and store it  in the variable i.(for example 1,2,3).

Second statement is   val += i; which can be written as val=val+i(this adds the numbers)....so after executing for loop final output would be 6

selected by

Related questions