Is there any difference between the below two functions 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;
}
With my testing in MSVC2008, both functions modifies the input array values. It seems both the functions are same in their functionality.
Can anyone give a case that need a reference to array in a function parameter?
Passing arrays to functions in C/C++ are passed by reference. Even though we do not create a reference variable, the compiler passes the pointer to the array, making the original array available for the called function's use. Thus, if the function modifies the array, it will be reflected back to the original array.
In the case of Call by Value, when we pass the value of the parameter during the calling of the function, it copies them to the function's actual local argument. In the case of Call by Reference, when we pass the parameter's location reference/address, it copies and assigns them to the function's local argument.
Like all Java objects, arrays are passed by value ... but the value is the reference to the array. Real passing by reference involves passing the address of a variable so that the variable can be updated.
Use pass by value when when you are only "using" the parameter for some computation, not changing it for the client program. In pass by reference (also called pass by address), a copy of the address of the actual parameter is stored.
The first one decays to a pointer to the first element in the array, the second is an actual reference to the array.
They're different in the same way that pointers and references are generally different.
Specifically, in the case of arrays, a reference to the array 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 you would in a C API.
One way of implementing this that I think is particularly slick involves templates. Using a template parameter, you can get the compiler to automatically deduce the size of the array. For example:
void ProcessArray(int* pArray, std::size length)
{
for (std::size_t i = 0; i < length; ++i)
{
// do something with each element in array
}
}
template <std::size_t N>
void ProcessArray(int (&array)[N])
{
ProcessArray(array, N); // (dispatch to non-template function)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With