quantum231
quantum231

Reputation: 2591

variable argument list program behaving strangely - cstdarg

This program gives the correct result just once. I have been trying to understand how the macros in cstadarg can be used to create and call functions that have a variable number of arugments.

#include <iostream>
#include <cstdarg>
using std::cout;
using std::endl;

int sum(int count, ...)
{

    if(count <= 0)
    return 0;

    va_list myarg_ptr; //create pointer to argument list
    va_start(myarg_ptr, count); // initate pointer to argument list

    int sum(0);

    for(int i=0; i<count; i++)
        sum += va_arg(myarg_ptr, int); // use and increment pointer to arugment list

    va_end(myarg_ptr); // set argument list pointer to NULL 
    return sum;
}


int main(int argc, char* argv[])
{
    cout << sum(9, 11, 22, 33, 44, 55, 66, 77, 6) << endl;
    cout << sum(6, 2, 4, 6, 8, 10, 5) << endl;
    cout << sum(9, 1, 2) << endl;

    std::system("pause");
    return 0;
}

The output I get is:

273156986
35
-173256537
Press any key to continue...

Upvotes: 1

Views: 167

Answers (3)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153955

The first argument you explicitly mention in the portotype is the part of the arguments! If you want to get the count passed to you function you need to explicitly pass it yourself, e.g., the last call should look like this:

std::cout << sum(3, 9, 1, 2) << '\n';

(you should also stop excessive use of std::endl).

A possibly preferrable C++2011 approach could be the use of a proper variadic argument list:

template <typename T>
int sum(T value) { return value; }
template <typename T, typename... S>
int sum(T value, S... values) { return value + sum(values...); }

Variadic argument lists can correctly detect the number of arguments. When using variable argument lists you need to get the list of detected arguments exactly right which is sometimes nont entirely trivial.

Upvotes: 0

P0W
P0W

Reputation: 47824

Fix your sum() call , number of elements for summing should the first argument for sum()

so,

cout << sum(8, 11, 22, 33, 44, 55, 66, 77, 6) << endl; //8 arguments
cout << sum(6, 2, 4, 6, 8, 10, 5) << endl; // 6 arguments
cout << sum(2, 1, 2) << endl; //2 arguments

Upvotes: 1

trojanfoe
trojanfoe

Reputation: 122411

The first argument to sum() is the number of following (variable) arguments. You aren't calling the function with the correct value the first and third time.

You want:

cout << sum(8, 11, 22, 33, 44, 55, 66, 77, 6) << endl;
cout << sum(6, 2, 4, 6, 8, 10, 5) << endl;
cout << sum(2, 1, 2) << endl;

Upvotes: 1

Related Questions