Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which way is better to pass arrays as function arguments in C?

There are 3 ways to pass arrays as function arguments.

  • Formal parameters as a pointer, e.g., void myFunction(int *param) {}
  • Formal parameters as a sized array, e.g., void myFunction(int param[10]) {}
  • Formal parameters as an unsized array, e.g., void myFunction(int param[]) {}

Which way is better in terms of efficiency and readability?

like image 259
SparkAndShine Avatar asked Dec 07 '22 10:12

SparkAndShine


1 Answers

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]);
like image 89
chux - Reinstate Monica Avatar answered Feb 16 '23 02:02

chux - Reinstate Monica