C Programming - Variable Number of Arguments - Discussion

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

int main()
{
    display(4, 'A', 'B', 'C', 'D');
    return 0;
}
void display(int num, ...)
{
    char c, c1; int j;
    va_list ptr, ptr1;
    va_start(ptr, num);
    va_start(ptr1, num);
    for(j=1; j<=num; j++)
    {
        c = va_arg(ptr, int);
        printf("%c", c);
        c1 = va_arg(ptr1, int);
        printf("%d\n", c1);
    }
}
A, A
B, B
C, C
D, D
A, a
B, b
C, c
D, d
A, 65
B, 66
C, 67
D, 68
A, 0
B, 0
C, 0
C, 0
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
9 comments Page 1 of 1.

Anusha said:   1 decade ago
How to read this values?

Kirthu said:   1 decade ago
va_list is used to collect the number of var arguments passed.
So, va_list ptr is a pointer used to traverse the var arguments.
Do ptr and ptr1 will contain 5.
va_start points to the first argument in the arg list.
Therefore, both ptr and ptr1 will point to 4 initially.
va_start(ptr,num)// (4,5)
va_start(ptr1,num)// (4,5)

Now inside the for loop,
For loops runs until it becomes equal to the num (5)

va_arg is used to move to the next arg in the list.
c=va_arg(ptr,num) // (4,5)
So it moves to point the arg next to 4 which is "A"
"%c" is used to print a char, therefore "A" is printed in first printf()

Same happens in c1 but since in the printf of c1,
"%d" which is used to print int ASCII val of "A" will be printed

So the out for first run of for loop will be

A , 65

Hence for all :)

Hope it helped:)

Vanita said:   1 decade ago
I did not understand this problem. Can anyone explain it briefly?

Nuzhat said:   1 decade ago
va_list ptr n prt1 are argument pointer to traverse through the variable arguments passed in the function....
va_start points ptr n ptr1 to the argument...in this case 4...

Preety said:   1 decade ago
va_list ptr, ptr1;
va_start(ptr, num);
va_start(ptr1, num);


Can anybody please tell me what's the purpose of this thing in code?

PULKIT AGGARWAL said:   1 decade ago
The function va_arg() extracts the argument from the argument list and advances the pointer to the next argument .

Here initially c=A and c1=A (but since it is %d therefore its ASCII value is printed).

Priya said:   1 decade ago
I didn get you. Can you please explain more clearly.

Sankar said:   1 decade ago
Here ptr and ptr1 are separate va_list,
ptr reads the parameter and displays in char format, and
ptr1 reads the parameter and displays in int format i.e. ASCII of A, B, C, and D.

Naveen said:   1 decade ago
Can someone tell how this code works??

Post your comments here:

Your comments will be displayed after verification.