I have an array of color codes, the size of which is known at compile time. I want to declare another array of the same size. But the code below throws an error.
I can, of course, declare the size as a global constant and then use that in the declaration of both arrays. But I don't want to keep adjusting the size constant when I add new colors. Is there a way to do this? (The variables are global.)
static const char *colors[] = {"#0000ff",
"#00ff00",
"#ff0000",
"#ffff00",
"#ff00ff",
"#00ffff",
"#ffffff",
"#000000",
"#ff8040",
"#c0c0c0",
"#808080",
"#804000"};
static const int NUM_COLORS = sizeof(colors) / sizeof(colors[0]);
static ColorButtons color_buttons[NUM_COLORS];
The size of a file scope array, if specified, must be an integer constant expression. A variable qualified with const
does not qualify as such as expression (this differs from C++ which does allow this).
Instead of making NUM_COLORS
a variable, make it a preprocessor symbol:
#define NUM_COLORS (sizeof(colors) / sizeof(colors[0]))
The expression that this expand to is an integer constant expression, and can therefore be used as the size of an array.
The only thing you'll need to look out for is to make sure you don't redefine colors
at a lower scope where you would also use NUM_COLORS
.