SyntaxIsEvil
SyntaxIsEvil

Reputation: 87

How do I pass a list of values to a function expecting an array?

In my program I want to pass a few variables into a function and have that function run a for loop to write the data to console.

This is my code:

void WriteValue(int[] arr)
{
    for(auto c : arr)
        std::cout<<arr<<std::endl;
}

int main() 
{
    int a = 0;
    int b = 1;
    int c = 3;

    WriteValue(a,b,c);

    return 0;
}

I know this would work in C# with params, but I don't have that option. How do I get this to run in C++?

Upvotes: 1

Views: 147

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283654

Here's a very simple and flexible way:

#include <iostream>

template<typename T>
void WriteValue(const T& arr)
{
    for(auto c : arr)
        std::cout << c << std::endl;
}

int main() 
{
    int a = 0;
    int b = 1;
    int c = 3;

    WriteValue(std::array<int, 3>{a,b,c});
    // nicer C99 way: WriteValue((int[]){a,b,c});

    return 0;
}

If you only want to be able to pass a list of ints (and it has to be a brace-separated list, not an existing array), you can instead do

#include <iostream>
#include <initializer_list>

void WriteValue(const std::initializer_list<int>& arr)
{
    for(auto c : arr)
        std::cout << c << std::endl;
}

int main() 
{
    int a = 0;
    int b = 1;
    int c = 3;

    WriteValue({a,b,c});

    return 0;
}

Unfortunately, VS2012 doesn't support this. You can upgrade to Visual 2013 (the Express Edition and Community Edition are both free), or you can use a helper variable:

#include <iostream>

template<typename T>
void WriteValue(const T& arr)
{
    for(auto c : arr)
        std::cout << c << std::endl;
}

int main() 
{
    int a = 0;
    int b = 1;
    int c = 3;

    int args[] = { a, b, c };
    WriteValue(args);

    return 0;
}

Upvotes: 3

Related Questions