Difference between passing array by value and reference in C ++

Is there a difference between the two functions below test1 and test2

static int const MAXL = 3; void test1(int t[MAXL]) { for (int i = 0; i < MAXL; ++i) t[i] = 10; } void test2(int (&t)[MAXL]) { for (int i = 0; i < MAXL; ++i) t[i] = 10; } 

When testing in MSVC2008, both functions change the values โ€‹โ€‹of the input arrays. Both functions seem to be the same in their functionality.

Can someone give a case requiring an array reference in a function parameter?

+4
source share
1 answer

The first splits into a pointer to the first element in the array, the second - the actual link to the array.

They differ from each other so that pointers and links are generally different.

In particular, in the case of arrays, an array reference is useful because you retain the ability to determine the size of the array. This frees you from having to pass the size / length of the array as a separate parameter, as in the C API.

One way to implement this, which I find particularly attractive, is through templates. Using the template parameter, you can force the compiler to automatically output the size of the array. For instance:

 void ProcessArray(int* pArray, std::size length) { for (std::size_t i = 0; i < length; ++i) { // do something with all elements in array } } template <std::size_t N> void ProcessArray(int (&array)[N]) { ProcessArray(array, N); } 
+5
source

Source: https://habr.com/ru/post/1490617/


All Articles