C Programming - Variable Number of Arguments - Discussion

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

int main()
{
    fun("IndiaBIX", 1, 4, 7, 11, 0);
    return 0;
}
void fun(char *msg, ...)
{
    va_list ptr;
    int num;
    va_start(ptr, msg);
    num = va_arg(ptr, int);
    num = va_arg(ptr, int);
    printf("%d", num);
}
IndiaBIX 1 7 11 0
1
4
7
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
34 comments Page 1 of 4.

Praveen said:   1 decade ago
Sir I think va_start (ptr, msg) should hold 6.

And num must return 6. ?

Give me region how it work.

Riya said:   1 decade ago
can anyone explain this please......

Onkar tiwari said:   1 decade ago
If anyone can explain then please explain. I will grateful to you.

Virat said:   1 decade ago
Please explain this question.

Shiv said:   1 decade ago
va_list ptr is an argument pointer, used to traverse through the variable arguments passed in the function.

va_start points 'ptr' to the first argument, in this case 'IndiaBix'

Every call to va_arg moves the ptr to next variable argument.

Hence after 2 calls to va_arg, the pointer ends up at '7' and num is '4'.

Nita said:   1 decade ago
I am aggry with shiv.

Anshu said:   1 decade ago
Yes I also thinks what shiv z saying, dats correct.

Anjali said:   1 decade ago
Sir please explane how it comes.

Saurabh said:   1 decade ago
I didn't get it ! Can anyone expalin in little more detail ?

Irshad said:   1 decade ago
#include<stdio.h>
#include<stdarg.h>
void irshad(char *arr, ...)
{
int num;
va_list ptr; /* create a new list ptr */
va_start(ptr,arr); /* attach ptr with arr */
printf("\n num=%d",arr); /* it will print 1st argument */
num = va_arg(ptr,int); /* fetch 2nd argument */
printf("\n num=%d",num);
num = va_arg(ptr,int); /* fetch 3rd argument */
printf("\n num=%d",num);
}
int main()
{

printf("\n variable argument:");
irshad(10,20,30,40,50,0);
return 0;
}


/* output */

variable argument:
num=10
num=20
num=30


Please let me know if any problem to understand this one.
irshadalam.mca[at]gmail.com


Post your comments here:

Your comments will be displayed after verification.