4

Why is it not possible to declare an array outside of a function with variables as size parameters in C99?

For example, consider this code snippet. It results in an error: variably modified ‘matrix’ at file scope compile error.

static int const height = 5;
static int const width = 5;
static int const matrix[height][width] = { ... };

int main(void){ ... }

I know that const in c doesn't mean constant. It means "read only", but I don't properly understand what implications this have. So why can't arrays get their size from read-only memory?

I know this problem can be solved using #defines or enum so i am more interested in an explanation as to why this is the case.

user694733
  • 15,208
  • 2
  • 42
  • 68
SørenHN
  • 566
  • 5
  • 20
  • Are you required to use C 1999? If you do not have a specific requirement to use C 1999, you should prefer the latest version of the standard, which is now the 2018 version. – Eric Postpischil Oct 02 '18 at 13:11
  • 3
    Because this is how C is defined. The language has a burdensome old rule that an array size (at file scope) must be an _integer constant expression_, which in turn restricts what you can use as array size. It's to be regarded as a language bug. C++ has fixed the bug, C has not. – Lundin Oct 02 '18 at 13:13
  • @EricPostpischil, yes C99 is required for this project. – SørenHN Oct 02 '18 at 13:15
  • Consider a tighter meaning than `const` means "read only". `const` means it is UB to attempt to change. It could "work". Given that, `static int const matrix[height][width]` does not represent a fixed size array with `static int const height = 5`. In order for `matrix[height][width]` to be a fixed size, `height` must be constant and `const` does not specify that. – chux - Reinstate Monica Oct 02 '18 at 14:37
  • The canonical may be *[Variably modified array at file scope in C](https://stackoverflow.com/questions/13645936/variably-modified-array-at-file-scope-in-c)*. – Peter Mortensen Jul 29 '23 at 09:40

1 Answers1

1

C99 6.7.5.2/2 Array declarators:

Only ordinary identifiers (as defined in 6.2.3) with both block scope or function prototype scope and no linkage shall have a variably modified type. If an identifier is declared to be an object with static storage duration, it shall not have a variable length array type.

Swordfish
  • 12,971
  • 3
  • 21
  • 43
  • I think the point here is not to use the array as a VLA, but rather why a `const` qualified variable can't be used as array size. – Lundin Oct 02 '18 at 13:19