Passing arrays to functions, what is the difference between these two approaches?

Viewed 84

In the example below, both functions return the same result. Can someone please explain what the difference is between them?

#include <iostream>

void func1( int (&a)[4]) {
    int b = a[3];
    std::cout << b << std::endl;
}

void func2( int a[4]) {
    int b = a[3];
    std::cout << b << std::endl;
}

int main()
{
    int b[4] = {3,2,3,4};
    func1(b);
    func2(b);
    return 0;
}
2 Answers

In func2, int a[4] is equivalent to int *a, in other words, 4 does not matter at all. You can pass an array of any size to to this function.

However, for func1, you have to pass it an array of size 4 or you will get a compilation error.

For example, if you feed func1 an array of size 8, you will get this compliation error,

main.cpp:26:12: error: invalid initialization of reference of type ‘int (&)[4]’ from expression of type ‘int [8]’ regardless of what the array size you feed to the function is.

Also, if you print the output of sizeof(a) function in func1, it will return the size of the input array in bytes, in this case, 16=4*4 bytes. For func2, it retunrs the size of a, which is a pointer to int (in my case that size is 8 bytes).

The first one won't accept any type except a reference to an array of 4 int elements while the second will accept a pointer to int or an array of unspecified size of int because it will be passed as an array.

Note also the first approach doesn't accept temporaries arguments so you can't do something like :

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

But if you want to use temporaries you could write :

void func1( int (&&a)[4])

Related