r/cprogramming • u/FrenchJJC • Feb 14 '26
Variable size array initialization
Howdy, I had a question about why my C code throws a 'variable size array initialization' for this expression:
int row = 2;
int const col = 3;
int array[][col] = {
initial value...
};
The guy in the video I was following along with managed to compile with this expression, but I had to change my 'col' from int const to a #define statement, which feels tacky. Is it an issue with compiler version? The compile statement I'm using is just a simple one, 'gcc -o output arrays.c'.
3
Upvotes
6
u/tstanisl Feb 14 '26
You can use anonymous enum to declare a true constant in C.
enum { col = 3 };
Starting from C23 standard one can use a bit more convenient:
constexpr int col = 3;
2
u/The_Ruined_Map Feb 14 '26 edited Feb 14 '26
In C language (as opposed to C++)
constdoes not produce constant expressions. For this reason, the size in your array declaration is not a constant expression. Your array is a VLA.In C constant expressions are produced by literal constants (e.g.
42), enum constants,sizeofand_Alignofexpressions,offsetofand such.1
u/HashDefTrueFalse Feb 14 '26
In C consts aren't constants, the effect is more like read only or turning off assignment.
colisn't a constant. Arrays need a constant, which is why the macro works fine. I don't use a recent enough C standard to know for sure if a later C standard changed this (I'm thinking maybe C23 but I could be making that up).Using macros is the usual way to do this in C. Google for recent additions to the language and use the
-std=compilation option if so.1
u/smokebudda11 Feb 15 '26
The #define is a macro which is a pre-processor directive. It’s not necessarily a const but shares a similar objective. Plus it’s easier to use across the code base instead of making the const a global and having to extern.