Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Passing an array directly into a function without initializing it first

Tags:

c++

arrays

Lets say you have created this function:

void function(int array1[2], int array2[2])
{
    // Do Something
}

Is it possible to do something like this in C++

function([1,2],[3,4]);

Or maybe this can better described as

function({1,2},{3,4});

The only way I know of accomplishing this is to do:

int a[2] = {1,2};
int b[2] = {3,4};
function(a,b);
like image 538
tysonsmiths Avatar asked Mar 31 '15 04:03

tysonsmiths


2 Answers

In c++11 you could do it this way:

void function(std::array<int, 2> param1, std::array<int, 2> param2)
{

}

call it as

function({1,2}, {3,4});
like image 93
bashrc Avatar answered Sep 27 '22 15:09

bashrc


If you don't want to use std::array for some reason, in C++11 you can pass the arrays by const reference:

// You can do this in C++98 as well
void function(const int (&array1)[2], const int (&array2)[2]) {
}

int main() {
    // but not this
    function({1, 2}, {3, 4});
}

For readability function can be rewritten as:

typedef int IntArray[2];
// or using IntArray = int[2];

void function(const IntArray& array1, const IntArray& array2) {
}
like image 27
Anton Savin Avatar answered Sep 27 '22 17:09

Anton Savin