It is sad to say so but there is some real
and terrible stupidnes in c99. When i wrote
programs in c (and I am involved c user) I
just use const int for array boundaries but
in c99 (and some previous too, terribly) it
will not compile (see for example
http://stackoverflow.com/questions/1712592/variably-modified-array-at-file-scope ) It is terribly wrong
thing for ppl who just wants to use const int to this
purposes and not to use preprocesor - as I do.
It is terribly stupidness in my opinion, it have to
be changed.
In C++, a const object initialized with a constant expression can itself
be used as a constant expression, but in C, this is not the case, and it
has never been the case. You're wrong when you claim to have previously
written C programs where such code worked. Perhaps you actually compiled
them as C++?
I like this feature of C++, and favor it's adoption in C. It would not
break any strictly conforming code, and would allows better type safety
than is provided by the C alternatives. However, describing this as a
stupid feature of C ignores the fact that C does provide perfectly
workable alternatives, such
#define CONSTANT 4
or
enum {CONSTANT=4};
Constant expressions are required in the following cases (and possibly
others that I missed):
_Alignas(CONSTANT)/*C2011*/ static struct {
unsigned bit_field:CONSTANT
} array[CONSTANT] = {
[CONSTANT/2].bit_field /*C99*/ = CONSTANT
};
enum {OTHER=CONSTANT};
case CONSTANT:
#if CONSTANT
#elif CONSTANT
_Static_assert(CONSTANT, "CONSTANT is 0"); /*C2011*/
C99 didn't make this issue any worse - in fact, C99 no longer required
the use of constant expressions for array dimensions unless the array
was defined with static storage duration (as was the case in your code)
(in C2011, constants are also required for the dimensions of arrays with
thread storage duration). When you don't use a constant expression, the
result is a Variable Length Array, as was mentioned in the title of your
stackoverflow question.
As a result, if you need to have global access to the array (which
suggests that your program is poorly designed), there is another
alternative in C99 or later:
types.h:
static const int NUM_TYPES = 4;
extern int *types;
main.c:
#include <types.h>
int *types;
int main(void)
{
int type_list[NUM_TYPES] = {
1,
2,
3,
4 };
types = type_list;
// The rest of your program.
}
Is there any reason why none of the C alternatives described above would
be acceptable for use in your program?