Coding Call
Coding Call

Reputation: 3

How to initialize a va_list object in c++?

This is getting annoying

I was long enough trying to fix this, but i have to ask you how to fix this because I have no ideas anymore.

#include <iostream>
#include <cstdarg>

using namespace std;

void add(const int &number, ...)
{
    double sum = 0.0;
    va_list list;

    va_start(list, number);
    for (int i = 0; i < number; i++)
        sum += va_arg(list, double);

    va_end(liste);

    cout << "Sum: " << sum << endl;
}

int main()
{
    add(12, 12);
}

This is my code. I get the error, that list ist not initiaized and i get the error, that the va_start argument must not have reference type and it must not be parenthesized. pls help

Upvotes: 0

Views: 1370

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

In your version, you're supposed to first pass the number of arguments as an integer value and then pass double values (since you interpret them as double). Passing int and interpreting as double as in your example causes undefined behavior. Here's the fixed version:

#include <iostream>
#include <cstdarg>

void add(int count, ...) 
{
    double sum = 0.0;
    std::va_list args;
    va_start(args, count);
    for (int i = 0; i < count; ++i) {
        sum += va_arg(args, double);
    }
    va_end(args);

    std::cout << sum << '\n';
}

int main() 
{
    add(4, 25.0, 25.0, 25.0, 25.0);
}

Here's a type-safe solution which works even if you mix ints and doubles:

#include <iostream>

template <typename... Args>
void add(Args... args)
{
  std::cout << (args + ...) << '\n';
}

int main()
{
    add(25.0, 25, 25.0, 25);
}

Upvotes: 2

Related Questions