liveBook · Manning

Variable-length array parameter

As explained in Modern C

A variable-length array parameter is a C array-parameter declaration whose element bound is determined from a runtime value.

void func(size_t n, double a[n]); declares a function receiving a pointer to a collection whose element count is supplied at runtime. The bound expresses the intended collection size rather than a fixed constant. section 15.0

Three collection-size contracts

Use void func(double a[static 7]); when the argument must point to at least seven elements. Use void func(size_t n, double a[n]); when the collection size is unknown until the call. Use void func(double *a); when the function accepts a pointer to one object or a null pointer. section 15.0

TAKEAWAY: choose the parameter notation that states the required object collection.

  • Treat the VLA form as an interface description for a runtime-sized collection, while recognizing that compiler diagnostics for misuse may be limited. section 15.0
  • Distinguish a VLA parameter from a static minimum and from a nullable pointer; each communicates a different precondition. section 15.0
void func(size_t n, double a[n]);
!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":4}],[{\"line\":0,\"ch\":10},{\"line\":0,\"ch\":16}],[{\"line\":0,\"ch\":20},{\"line\":0,\"ch\":26}]]"}
!@%STYLE%@!

Inspect the compact VLA declaration directly: the preceding size_t parameter supplies the runtime bound. section 15.0

How Modern C covers it

How deep it goes
Defines the syntax through contrasting declarations and notes limited compiler checking, but does not develop implementation internals.
Examples
Shows void func(size_t n, double a[n]) alongside static-seven and plain-pointer declarations.
What you can do after
Apply via C declarations a runtime-sized collection contract and distinguish it from fixed-minimum or nullable-pointer interfaces.
How it connects
Connects variable-length array parameters with pointers, array parameters, static minimum bounds, and null pointers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.