C Programming - Variable Number of Arguments - Discussion

Discussion Forum : Variable Number of Arguments - Find Output of Program (Q.No. 3)
3.
What will be the output of the program?
#include<stdio.h>
#include<stdarg.h>
void dumplist(int, ...);

int main()
{
    dumplist(2, 4, 8);
    dumplist(3, 6, 9, 7);
    return 0;
}
void dumplist(int n, ...)
{
    va_list p; int i;
    va_start(p, n);

    while(n-->0)
    {
        i = va_arg(p, int);
        printf("%d", i);
    }
    va_end(p);
    printf("\n");
}
2 4
3 6
2 4 8
3, 6, 9, 7
4 8
6 9 7
1 1 1
1 1 1 1
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
20 comments Page 1 of 2.

Akshaya Shelke said:   8 years ago
Thanks for your explanation @Vvvvvvv.

Mahi said:   8 years ago
Decrement value of n.

Untill (n--) to 0.

Teju said:   9 years ago
while(n-->0) Explain this line.

Sandipan said:   9 years ago
What is va_end?

Vvvvvvv said:   9 years ago
In the list, the first parameter always represents the number of arguments to be passed.

So the 2 in the first function represents that there are 2 arguments.

And 3 in second function represents there are 3 arguments.

So first it prints 4 and 8.

Next, it will print 6, 9, 7. Excluding 4 and 8.
4 and 8 are actually to define a number of parameters. And they are not get printed.

Vinayk patil said:   10 years ago
In both dumplist 2, 3 initial values represent no of arguments taken remaining are values stored so n->0 indicates for 1st while (n->0) indicates n is equal to 0 for both times of dumplist.

It is checked but initial value of n=2 no of arguments taken by dumplist accordingly n=3 for 2nd one n--is done according to printf function respective values included initially is printed.

Anonymous said:   1 decade ago
Here first variable passed in both calls will be considered as the starting point to work with variable list.

In first part,

va start : 2.

So n would be, 2 so loop runs for 4 and 7.

Whereas in second case, va start:3 so 6 9 and 7 is printed on the screen.

Kalpana said:   1 decade ago
I need a clear explanation about this program.

Priya said:   1 decade ago
I can't understand, please anyone explain the above program clearly.

Rahul said:   1 decade ago
Can anyone please explain this in detail.

@Raj well, ques2 also talks about the same concept, but here, va_arg doesn't seem to point to the next argument.


Post your comments here:

Your comments will be displayed after verification.