Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the size of an array passed to a function by reference known to the compiler in C++?

I know that when I want to pass an array to a function, it will decay into pointer, so its size won't be known and these two declarations are equivalent:

void funtion(int *tab, int size);

and

void funtion(int tab[], int size);

And I understand why. However, I checked that when I pass an array as a reference:

void funtion(int (&tab)[4]);

the compiler will know the size of the array and won't let me pass an array of different size as an argument of this function.

Why is that? I know that when I pass an array by address, the size isn't taken into account while computing the position of the ith element in the array, so it is discarded even if I explicitly include it in the function declaration:

void funtion(int tab[4], int size);

But what is different when I pass an array by reference? Why is its size known to the compiler?

Note: I'm interested in arrays whose size is known at compile time, so I didn't use any templates.

I found a similar question on Stack Overflow, however it doesn't answer my question - it doesn't explain why the compiler knows the size of the array, there is just some information on how to pass arrays to functions.

like image 627
user2738748 Avatar asked Mar 10 '16 17:03

user2738748


1 Answers

Because it can, and because checking adds extra safety. The compiler knows the size of the array because you tell it so, right there in the function declaration. And since that information is available, why wouldn't it use it to signal errors in your source code?

The real question is why your last example wouldn't do the same check. This is, unfortunately, another piece of C legacy - you are never passing an array, it always decays into a pointer. The size of the array then becomes irrelevant.

Could a check be added? Possibly, but it would be of limited use (since we are all using std::array now - right!?), and because it would undoubtedly break some code. This, for example:

void func (char Values [4]);
func ("x");

This is currently legal, but wouldn't be with an additional check on array size.

like image 108
H. Guijt Avatar answered Nov 15 '22 03:11

H. Guijt