Ankur
Ankur

Reputation: 350

va_list not working properly

I have written a code:

 void xy(int a,...)
    {
    va_list list;
    va_start(list,a);
    int result=0;//va_start(list,x);

    for(;;)
    {
            int p=va_arg(list,int);
             cout<<p<<endl;
            if(p==0)
            break;

            result+=p;
    }

    va_end(list);
    cout<<result<<endl;
  }

and called this function : xy(20,30,40);

I am expecting 20, 30, 40 will be printed. and their sum. but it is printing :

30 40 13336564 11872144 -3271312 -3271224 12029596 11926688 134527888 -3271224 12029596 1 -3271180 -3271172 11929640 0 191296075

don't know why.

Please suggest some solution.

Upvotes: 0

Views: 1047

Answers (1)

gnasher729
gnasher729

Reputation: 52622

Well, your code is really clever, isn't it? You are checking for a zero to mark the end of the parameter list. However, you are calling the function with a parameter list that doesn't end with or contain a zero. Where do you think would the zero come from that you are checking? Call instead

xy (20, 30, 40, 0);

bluebell's comment is obviously nonsense. THERE IS NO WAY TO DETECT THAT THERE ARE NO MORE ARGUMENTS. Caller and callee have to agree how to detect the end of the argument list, and then of course the caller has to send the write parameters.

printf does this by the caller sending a format string that the printf function will examine. Or you could send the number of arguments as the first parameter, so a function calculating the average of n values could be called as

average (1, 3.7);
average (3, 3.7, 4.1, 4.2);

20 is not printed because 20 is sent as the named argument, so your sum should start with the value a. 30 and 40 are received through the va_arg macro, as will be the number 0 if you pass it as a parameter - if you don't pass that number, your code will continue reading data from random memory locations until by chance it reads memory containing a number 0.

As another example: When you call printf ("%d %d\n", 4, 5); the printf function gets the format string "%d %d\n" as the first parameter. It examines this string and finds the letters %d twice, so it means there must be two int parameters. If you didn't supply two int parameters, you would expect rubbish to be printed.

Upvotes: 1

Related Questions