In C, why can’t a const variable be used as an array size initializer? [duplicate]

This is because in C const actually means read only. Quoting C FAQ 1.18 and 1.19:

The const qualifier really means “read-only”; an object so qualified is a run-time object which cannot (normally) be assigned to. The value of a const-qualified object is therefore not a constant expression in the full sense of the term, and cannot be used for array dimensions, case labels, and the like. (C is unlike C++ in this regard.) When you need a true compile-time constant, use a preprocessor #define (or perhaps an enum).

References: ISO Sec. 6.4
H&S Secs. 7.11.2,7.11.3 pp. 226-7

There are two ways of dealing with it:

  1. Use #define instead of const
  2. Use enum { sz = 12 };

Leave a Comment