简体   繁体   中英

Variable number of arguments in C++ [Xcode]

I have a problem with variable number of arguments in C++. I write my code using Xcode.

Here is my code:

#include <iostream>

int sum(int n, ...)
{
    int *p = &n;
    p++;

    int res = 0;
    for(int i=0; i<n; i++){
        res+=(*p);
        p++;
    }

    return res;
}

int main(int argc, const char * argv[]) {

    std::cout << sum(4, 1, 2, 3, 4);

    return 0;
}

sum(4, 1, 2, 3, 4) should return a value of 10, but it returns 1606452732.

In C++ you use a template metafunction to do that. It's pretty straight forward:

int sum(int u)
{return u;}  // Recursion-End

template<typename... Args>
int sum(int u, Args... rest)
{
    return u + sum(rest...);
}

Try it online !

However there is a, as I consider it, depreciated C-way using va_start and va_end . You need to include cstdarg and on function call you need to provide the total parameter count. It would look like this:

int sum(int argnum, ...)
{
    va_list arguments;
    int i;
    int sum = 0;

    va_start(arguments, argnum); /* Needs last known character to calculate
                                    the address of the other parameters */
    for(i = 0; i < argnum; ++i)
        sum += va_arg(arguments, int); /* use next argument */

    va_end(arguments);

    return sum;
}

Try it online !

From: http://en.cppreference.com/w/cpp/utility/variadic/va_start

#include <iostream>
#include <cstdarg>

int add_nums(int count, ...) 
{
    int result = 0;
    va_list args;
    va_start(args, count);
    for (int i = 0; i < count; ++i) {
        result += va_arg(args, int);
    }
    va_end(args);
    return result;
}

int main() 
{
    std::cout << add_nums(4, 25, 25, 50, 50) << '\n';

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM