9

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?

1
  • 4
    There is no pass by value for arrays in either C or C++. Unless you use a C++ reference, they are passed as pointers to their first element. Commented Jul 10, 2013 at 4:36

1 Answer 1

7

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)
}
Sign up to request clarification or add additional context in comments.

4 Comments

Can you elaborate on the last part - the reference help in determining the size?
@FaisalM Your first example only passes a pointer, so you lose the information about the array's size in the context of that function. The sizeof operator will return only the size of the pointer. If you pass a reference to the array, you can still determine its size using the sizeof operator inside of the function.
Worth (IMHO) at least a small mention that the template code will be instantiated for every size of array passed, which could be pretty wasteful. That can easily be addressed by having ProcessArray call a non-templated support function ala ProcessArrayImpl(array, N); where ProcessArrayImpl takes (int*, size_t) - i.e. layering the two approaches from the question.
@Tony Agreed, that's what I usually do. I suppose it is worth a mention, I was just trying not to overcomplicate the example. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.