Home > Blockchain >  Reusing variable in function parameter list
Reusing variable in function parameter list

Time:11-26

int doSomething(int n, int arr[n])

What confuses me here is the reusing of the n variable inside the parameter list. Can anyone explain why this is valid and what are the use cases?

CodePudding user response:

It is valid.

For this specific case it is equivalent to:

int doSomething(int n, int arr[]);
int doSomething(int n, int *arr);

because the array parameters are automatically transformed into pointers to arrays' elements. In general there are a few differences between array-like and pointer declarations of parameters. See link for more details.

IMO, the better usage should be:

int doSomething(int n, int arr[static n]);

This static n tell the compilers that at least n elements pointer by arr are valid. Moreover it makes the declaration visually different from a declaration of array what helps to avoid surprising issues when sizeof arr is used.

CodePudding user response:

C allows several syntaxs for passing an array pointer including:

 int* arr, int arr[] or int arr[10]  

However ALL of these are equivalent to the first - that is the compiler sees only an int pointer and does not use any size that may have been specified in the array square brackets to enforce integrity on the size of the array passed. In all the above cases the compiler will generate:

void __cdecl foo(int * const)

The only way to specify the size of an array is, as you have done, pass a separate parameter indicating the size/length of the array.
In the example you cite the n in arr[n] is not used by the compiler to maintain any integrity on the array bounds - in the example it is only included as an indication that the first parameter is the size. A less controversial form of the same code might be just to state that more explicitly:

int doSomething(int arr_len, int arr[])

In terms of what is the best convention or preference for passing an pointer and its array size see this question.

  •  Tags:  
  • c
  • Related