0

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

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • Does this answer your question? [How do I fill a va\_list](https://stackoverflow.com/questions/13703770/how-do-i-fill-a-va-list) – Tarek Dakhran Mar 08 '20 at 13:27
  • The main problem is that you call the `add` function with two *integer* values. More specifically two `int` values. I don't know any system where `sizeof(int) == sizeof(double)`, which means you will have *undefined behavior* in the `add` function. – Some programmer dude Mar 08 '20 at 13:30
  • No reproduction, `list` is initialized (or rather filled) prior to use here. There is a typo in `va_end(liste);` though and types of arguments passed are not matching extracted values. – user7860670 Mar 08 '20 at 13:31

1 Answers1

2

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);
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93