Reputation: 35
I recently saw a function written in the following form void func(int size, int a[size]){ ... }
and I was curious about the argument a[size]
. At first I thought maybe it had something to do with indexing the array, but running the code a
was in fact an array. Then I thought maybe it had to do with the size of the array, so I tried passing in different value and seeing if it would affect the array length, but it seemed not to (unless maybe it had something to do with writing past the array, but this feels unlikely). So my question is essentially, what does the "index" do in the function arguments?
Upvotes: 2
Views: 779
Reputation: 782130
It's the array size, but it's ignored when it's in a function parameter declaration. A function parameter of the form int a[size]
or int a[]
is treated identically to int *a
, because arrays decay to pointers when used as function arguments.
So it's essentially just a form of self-documentation. The caller is supposed to pass an array that contains size
elements.
Note that this only applies to the first dimension in a multidimensional array parameter. If you have something like
void func(int width, int height, int a[height][width]) { ... }
The width
part of the array declaration is used, but the height
is ignored. a
is a pointer to an array of int[width]
rows; the width is needed when indexing the first dimension.
Upvotes: 4