C Programming - Variable Number of Arguments - Discussion


What will be the output of the program?

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, A
B, B
C, C
D, D
[B]. A, a
B, b
C, c
D, d
[C]. A, 65
B, 66
C, 67
D, 68
[D]. A, 0
B, 0
C, 0
C, 0

Answer: Option C


No answer description available for this question.

Naveen said: (Sep 15, 2010)  
Can someone tell how this code works??

Sankar said: (Oct 22, 2010)  
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.

Priya said: (Jul 26, 2011)  
I didn get you. Can you please explain more clearly.

Pulkit Aggarwal said: (Aug 7, 2011)  
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).

Preety said: (Nov 16, 2011)  
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?

Nuzhat said: (Dec 6, 2011)  
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...

Vanita said: (Feb 9, 2012)  
I did not understand this problem. Can anyone explain it briefly?

Kirthu said: (May 19, 2012)  
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:)

Anusha said: (Dec 27, 2014)  
How to read this values?

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.