Passing an array by reference

C++Arrays

C++ Problem Overview


How does passing a statically allocated array by reference work?

void foo(int (&myArray)[100])
{
}

int main()
{
    int a[100];
    foo(a);
}

Does (&myArray)[100] have any meaning or its just a syntax to pass any array by reference? I don't understand separate parenthesis followed by big brackets here. Thanks.

C++ Solutions


Solution 1 - C++

It's a syntax for array references - you need to use (&array) to clarify to the compiler that you want a reference to an array, rather than the (invalid) array of references int & array[100];.

EDIT: Some clarification.

void foo(int * x);
void foo(int x[100]);
void foo(int x[]);

These three are different ways of declaring the same function. They're all treated as taking an int * parameter, you can pass any size array to them.

void foo(int (&x)[100]);

This only accepts arrays of 100 integers. You can safely use sizeof on x

void foo(int & x[100]); // error

This is parsed as an "array of references" - which isn't legal.

Solution 2 - C++

It's just the required syntax:

void Func(int (&myArray)[100])

^ Pass array of 100 int by reference the parameters name is myArray;

void Func(int* myArray)

^ Pass an array. Array decays to a pointer. Thus you lose size information.

void Func(int (*myFunc)(double))

^ Pass a function pointer. The function returns an int and takes a double. The parameter name is myFunc.

Solution 3 - C++

It is a syntax. In the function arguments int (&myArray)[100] parenthesis that enclose the &myArray are necessary. if you don't use them, you will be passing an array of references and that is because the subscript operator [] has higher precedence over the & operator.

E.g. int &myArray[100] // array of references

So, by using type construction () you tell the compiler that you want a reference to an array of 100 integers.

E.g int (&myArray)[100] // reference of an array of 100 ints

Solution 4 - C++

The following creates a generic function, taking an array of any size and of any type by reference:

template<typename T, std::size_t S>
void my_func(T (&arr)[S]) {
   // do stuff
}

play with the code.

Solution 5 - C++

Arrays are default passed by pointers. You can try modifying an array inside a function call for better understanding.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohn DBView Question on Stackoverflow
Solution 1 - C++ErikView Answer on Stackoverflow
Solution 2 - C++Martin YorkView Answer on Stackoverflow
Solution 3 - C++cpxView Answer on Stackoverflow
Solution 4 - C++User12547645View Answer on Stackoverflow
Solution 5 - C++Eduardo A. Fernández DíazView Answer on Stackoverflow