How the vararg function call works

I am trying to understand how a variational function works. I am reading man stdargand I am writing the following code:

#include <stdarg.h>
#include <stdio.h>

int sum(int count, ...){
    va_list lst;
    va_start(lst, count);
    printf("First=%i,Second=%i,Third=%i, Fourth=%i, Fifth=%i\n",va_arg(lst,int),va_arg(lst,int),va_arg(lst,int),va_arg(lst,int),va_arg(lst,int));
}

int main(){
    sum(1,2,3,4);
}

After compiling and working, I have the following input:

First=0,Second=134513840,Third=4, Fourth=3, Fifth=2.

I do not understand this. I expect First=2, Second=3, Third=4Fourth / Fifth to have an undefined value, because after calling the function, the arguments are pushed onto the stack from right to left and va_arg(lst, int)just return a pointer to an element that goes deeper on the stack.

+4
source share
2 answers

There are a few small mistakes (the first is what I hinted at in my comment):

  • ( printf()) ( ). , va_arg- .
  • count, .
  • , int.

:

#include <stdarg.h>
#include <stdio.h>
int sum(int count, ...){
    if(count!=5) { printf("this version expects 5 variable args"); return 1; }
    va_list lst;
    va_start(lst, count);
    int a1 = va_arg(lst,int);
    int a2 = va_arg(lst,int);
    int a3 = va_arg(lst,int);
    int a4 = va_arg(lst,int);
    int a5 = va_arg(lst,int);
    va_end(lst); // added for cleanup
    printf("First=%i,Second=%i,Third=%i, Fourth=%i, Fifth=%i\n", 
         a1, a2, a3, a4, a5);
    return 0;
}
int main(){
    sum(5, 1,2,3,4,5);
    return 0;
}
    // prints: First=1,Second=2,Third=3, Fourth=4, Fifth=5

, , - 5, var-arg- , :

#include <stdarg.h>
#include <stdio.h>
int sum(int count, ...){
    va_list lst;
    va_start(lst, count);
    int i=0; for(; i<count; ++i) {
        printf("at %i is %i\n", i, va_arg(lst, int));
    }
    va_end(lst);
    return 0;
}
int main(){
    sum(5, 1,2,3,4,5);
    return 0;
}
+4

.

#include <stdarg.h>
#include <stdio.h>

int sum(int count, ...){
    va_list lst;
    va_start(lst, count);
    int first=va_arg(lst,int),second=va_arg(lst,int),third=va_arg(lst,int),fourth=va_arg(lst,int),fifth=va_arg(lst,int);
    printf("First=%i,Second=%i,Third=%i, Fourth=%i, Fifth=%i\n",first,second,third,fourth,fifth);
}

int main(){
    sum(5,1,2,3,4,5);
}
0

All Articles