There are 3 ways to pass arrays as function arguments.
void myFunction(int *param) {}
void myFunction(int param[10]) {}
void myFunction(int param[]) {}
Which way is better in terms of efficiency and readability?
Which way is better to pass arrays as function arguments in C?
I am going for Door #4. The receiving function needs to know the size.
void myFunction(size_t array_element_count, int *param);
Alternatively code could use a terminating sentinel, but there are no special "I-am-not-an-int" values.
In terms of the below, they emit the same code. This is a style issue. As such, follow the group's style guide. For me I favor size_t array_element_count, int param[array_element_count]
as most informative to code's intent.
void myFunction(size_t array_element_count, int *param);
void myFunction(size_t array_element_count, int param[array_element_count]);
void myFunction(size_t array_element_count, int param[]);
In terms of style, f(size, ptr)
vs f(ptr, size)
, I recall reading on the next C rev promoting f(size, ptr)
. IAC, with more complex arrays and VLA support , the below is useful:
foo(size_t row, size_t col, matrix[row][col]);
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