I don’t understand why the following example compiles and works:
void printValues(int nums[3], int length) {
for(int i = 0; i < length; i++)
std::cout << nums[i] << " ";
std::cout << '\n';
}
It seems that the size of 3 is completely ignored but putting an invalid size results in a compile error. What is going on here?
In C++ (as well as in C), parameters declared with array type always immediately decay to pointer type. The following three declarations are equivalent
I.e. the size does not matter. Yet, it still does not mean that you can use an invalid array declaration there, i.e. it is illegal to specify a negative or zero size, for example.
(BTW, the same applies to parameters of function type – it immediately decays to pointer-to-function type.)
If you want to enforce array size matching between arguments and parameters, use pointer- or reference-to-array types in parameter declarations
Of course, in this case the size will become a compile-time constant and there’s no point of passing
lengthanymore.