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?
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.
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