liveBook · Manning

Variable-length array

As explained in Modern C, Third Edition

A variable-length array is a C array whose bound is determined at run time rather than being an integer constant expression.

A variable-length array (VLA) is a C array whose bound is not an integer constant expression, so its size is determined at run time. VLAs were mandatory in C99, became optional in C11, and remain optional for automatic objects in C23; VLA types, pointers to them, and VLA parameters are mandatory in C23. section 6.1.3

Keep these declaration and usage rules in view:

  • Declare VLAs only inside functions; they cannot be declared outside functions. section 6.1.3
  • Give a VLA a strictly positive bound. section 6.1.3
  • Use only default initializers for VLAs. section 6.1.3
  • Distinguish VLAs from fixed-length arrays: a fixed-length array has a bound supplied by an integer constant expression or inferred from its initializer. section 6.1.3

A VLA's lifetime begins when execution encounters its definition and ends when its visibility scope is left. Unlike other automatic objects, it cannot be used earlier in the same block, because its storage cannot be allocated until its run-time size is known. section 13.3

VLAs consume dynamically determined function-context storage, commonly associated with the stack. Their size can make exhaustion difficult to estimate, although replacing a large fixed-length array with a VLA may reduce stack usage. The C standard provides no way to predict stack exhaustion; check __STDC_NO_VLA__ when portability matters. section 15.2.2

How Modern C, Third Edition covers it

How deep it goes
Descends from classification to initialization, scope, lifetime, and stack behavior, but does not develop a complete implementation example.
Examples
Uses array-length classification, initializer-based fixed arrays, a control-flow lifetime example, and stack-exhaustion scenarios.
What it assumes
Assumes familiarity with C arrays, scopes, automatic objects, integer constant expressions, and function-call storage.
What you can do after
Evaluate VLA declarations for validity, lifetime behavior, portability, and potential stack exhaustion.
How it connects
Connects VLAs with fixed-length arrays, integer constant expressions, automatic objects, variably modified types, and stack overflow.

Also explained in

Compare how 2 books explain variable-length array →

Related concepts

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