Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing variable in function parameter list

Tags:

c

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?

like image 512
Michael Munta Avatar asked Jan 20 '26 13:01

Michael Munta


1 Answers

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.

like image 172
tstanisl Avatar answered Jan 22 '26 16:01

tstanisl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!