Passing C++ arrays to function by reference

Question | Nov 19, 2015 | nextptr 

Talk of passing arrays to functions by reference in C++ is estranged by the fact that arrays in C++ are always passed by reference. What makes this subject interesting is to do with the way C++ compiles the array function parameters.

Here is the list of commonly used ways to pass arrays to functions:

void Foo(char *array);
void Foo(char array[]);
void Foo(char array[10]);

In all the above three cases, the array parameter does not have the size and dimension information of the passed array argument. You cannot get the size of array within Foo by merely calling sizeof(array), because that would return the size of a char pointer. In other words, a passed array argument to Foo is decayed to a pointer.

That is where the following lesser-known syntax to pass arrays by reference comes handy:

void Foo(char (&array) [100]);  // Yes, it is legal.      

Passing an array to a function that takes an array by reference, as shown above, does not decay the array to a pointer. In the above implementation of Foo, you can safely call sizeof(array) and it would return you 100.

As you are armed with this knowledge now, what do you think the output/outcome of the following would be:

void Increment(unsigned char (&a)[4]) {
    for( int i=0; i < sizeof(a)/sizeof(unsigned char); ++i)

int a = 0x01010101;
Increment( (unsigned char (&)[4])a );  // casting int to 'unsigned char' array reference.
std::cout << std::hex << "0x" << a << std::endl;

Select the correct answer below (please check Explanations for details on the answer):

2015 nextptr