C – Why Can’t Arrays Be Passed as Function Arguments?

chistory

Following this comment, I've tried to google why, but my google-fu failed.

Comment from link:

[…] But the important thing is that arrays and pointers are different things in C.

Assuming you're not using any compiler extensions, you can't generally pass an array itself to a function, but you can pass a pointer, and index a pointer as if it were an array.

You're effectively complaining that pointers have no length attached. You should be complaining that arrays can't be passed as function arguments, or that arrays degrade to pointers implicitly.

Best Answer

My first guess for the reason was simply because of performance and memory saving reasons, and for the ease of compiler implementation as well (especially for the kind of computers at the time when C was invented). Passing huge arrays "by value" seemed to have a huge impact at the stack, it needs a full array copy operation for each function call, and probably the compiler must be smarter to output the correct assembly code (though the last point is debatable). It would also be more difficult to treat dynamically allocated arrays the same way as statically allocated arrays (from the viewpoint of the language's syntax).

EDIT: after reading some parts from this link, I think the real reason (and the reason why arrays in structs are treated as value types, while sole arrays are not) is the backward compatibility to C's predecessor B. Here is the cite from Dennis Ritchie:

[...} The solution constituted the crucial jump in the evolutionary chain between typeless BCPL and typed C. It eliminated the materialization of the pointer in storage, and instead caused the creation of the pointer when the array name is mentioned in an expression. The rule, which survives in today's C, is that values of array type are converted, when they appear in expressions, into pointers to the first of the objects making up the array.

This invention enabled most existing B code to continue to work, despite the underlying shift in the language's semantics. [..]