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?
Passing the array size tells the function where the bounds are so you can choose not to go beyond them.
A whole array cannot be passed as an argument to a function in C++. You can, however, pass a pointer to an array without an index by specifying the array's name.
Variable length arrays are also known as runtime sized or variable sized arrays. The size of such arrays is defined at run-time. Variably modified types include variable length arrays and pointers to variable length arrays. Variably changed types must be declared at either block scope or function prototype scope.
If you create an array by initializing its values directly, the size will be the number of elements in it. Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array.
In C++ (as well as in C), parameters declared with array type always immediately decay to pointer type. The following three declarations are equivalent
void printValues(int nums[3], int length);
void printValues(int nums[], int length);
void printValues(int *nums, int length);
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
void printValues(int (&nums)[3]);
void printValues(int (*nums)[3]);
Of course, in this case the size will become a compile-time constant and there's no point of passing length
anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With