Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can one specify the size of an array in a function parameter?

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?

like image 300
defectivehalt Avatar asked Feb 16 '10 21:02

defectivehalt


People also ask

Why do we pass size of array into function?

Passing the array size tells the function where the bounds are so you can choose not to go beyond them.

Can an array be a function parameter?

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.

Can we define size of array with variable?

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.

Why can't you change the size of an array?

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.


1 Answers

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.

like image 184
AnT Avatar answered Sep 25 '22 19:09

AnT