Search code examples
cvariadic-functionsfunction-definition

Get the wrong answer——about uncertain number of variables


When I ran the program below in the Linux system, I can't get the expected answer "9". But I can get it in the windows system.

Why does this happen?

#include <stdio.h>

int sum(int num, ...){
    int* p = &num + 1;
    int res = 0;
    while(num--){
        res += *p++;
    }
    return res;
}


int main(){
    printf("%d\n", sum(3,2,3,4));
    return 0;

}

I debug it in GDB, shown as below: enter image description here

My System configuration is below.

Linux version 5.11.0-41-generic (buildd@lgw01-amd64-005) (gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, GNU ld (GNU Binutils for Ubuntu) 2.34)


Solution

  • You need to use macros defined in the header <stdarg.h>.

    Here you are.

    #include <stdio.h>
    #include <stdarg.h>
    
    long long int sum( size_t n, ... ) 
    {
        long long int result = 0;
    
        va_list ap;
    
        va_start( ap, n );
    
        while (n--)
        {
            result += va_arg( ap, int );
        }
    
        va_end( ap );
    
        return result;
    }
    
    int main( void )
    {
        printf( "%lld\n", sum( 9, 1, 2, 3, 4, 5, 6, 7, 8, 9 ) );
    }
    

    The program output is

    45