简体   繁体   中英

Getting garbage when using operator …

I'm trying to use operator "..." but getting troubles:

void Func(int diff, CTester* pcTester, int params ...)
{
    va_list ap;
    va_start(ap, params);
    for(int i = 0; i < params; i++) {
        int val = va_arg(ap, int);
        cout << "[" << i << "] = " << val << "\n";
        if (diff > val) {
            // some logic
        }
    }
    va_end(ap);
}

I'm calling Func in this way:

Func(1359, pcTester, 10, 20, 30, 40);

I expect to see in console the prints of [0]=10 [1]=20 [2]=30 [3]=40 But I'm getting too many prints:

[0] = 20
[1] = 30
[2] = 40
[3] = 4197568
[4] = 26221600
[5] = 0
[6] = 4196640
[7] = 4197568
[8] = 1152895024
[9] = 0

As you can see I have 10 prints (instead of 4) and the first value (10) is not in the list

What am I doing wrong ?

Your program has undefined behavior.

You are treating the argument params to be number of arguments following it but you are not passing enough arguments.

Func(1359, pcTester, 10, 20, 30, 40); // There are only 3 arguments after 10.

You need to make sure that they match. Use:

// 3 arguments after params
Func(1359, pcTester, 3, 20, 30, 40);

or

// 4 arguments after params
Func(1359, pcTester, 4, 10, 20, 30, 40);

or

// 10 arguments after params
Func(1359, pcTester, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110);

Better use C++ variadic templates and a std::initializer_list to fix the type to int .

#include <iostream>
#include <initializer_list>

class CTester {};

template < typename ... Args >
void Func(int diff, CTester* pcTester, Args ... params)
{
  int i = 0;
  for(int val : std::initializer_list<int>{ params ... })
  {
    std::cout << "[" << i << "] = " << val << "\n";
    if (diff > val) {
      // some logic
    }
    ++i;
  }
}

int main()
{
  CTester * pcTester = new CTester;
  Func(1359, pcTester, 10, 20, 30, 40);
  delete pcTester;
}

Demo on ideone

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