C/C++ va_list not returning arguments properly

拈花ヽ惹草 提交于 2019-12-03 16:41:49

In the context of a varargs call, float is actually promoted to double. Thus, you'll need to actually be pulling doubles out, not floats. This is the same reason that %f for printf() works with both float and double.

Since we are talking C++ here, you might want to use newer C++11 facilities.

I could suggest variadic templates, but it might be a bit too advanced, on the other hand to pass an arbitrary long list there now is std::initializer_list<T> where T is a simple type.

 void function(std::initializer_list<int> list);

It does not have many functions, just:

  • size() which returns how many elements are in the list
  • and begin() and end() which return iterators as usual

So you can actually do:

void function(std::initializer_list<int> list) {
    std::cout << "Gonna print " << list.size() << " integers:\n";

    bool first = true;
    for (int i: list) {
        if (first) { first = false; } else { std::cout << ", "; }
        std::cout << i;
    }
    std::cout << "\n";
}

And then invoke it as:

int main() {
    function({1, 2, 3, 4, 5});
}

which will print:

Gonna print 5 integers:
1, 2, 3, 4, 5

In general in C++, stay away from the C-variadic. They are type-unsafe and full of gotchas.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!