-1

I have variable in header:

const static int RED = 0;
const static int BLUE = 1;
const static int GREEN = 5;
const static int DOG = 8;
const static int CAT = 9;
const static int SNAKE = 7;

How can I create a global array and initialize them with the values of these const variables?

I tried:

const static int color[3] = {BLUE, GREEN, DOG};
const static int animal[3] = {DOG, CAT, SNAKE};

But compiler say error:

initializer element is not constant

(I need to create some structure which I can loop over.)

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
coupraes
  • 21
  • 1
  • 1
  • 3

2 Answers2

1

In C, using const does not make a variable a compile time constant. It is called const qualified. So, you cannot use a const variable for initializing the other one in global scope.

Related, from C11, chapter ยง6.7.9, Initialization

All the expressions in an initializer for an object that has static or thread storage duration shall be constant expressions or string literals.

So, to get your job done, you can either make the RED, BLUE as MACROs (using #define), or, an enum, using these identifier names as enum constants.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Good explanation. BTW, when I tested the code with gcc (Apple LLVM version 6.1.0 (clang-602.0.53)), the compiler did not complain.it seems wired. โ€“ Eric Tsui Jul 09 '15 at 09:53
1

What you could do is define them, so the values are constant at compile time:

#define RED 0
#define BLUE 1
#define GREEN 5

const static int color[3] = {BLUE, GREEN, DOG};

Or you could just set all elements in the array at runtime:

const static int color[3];
color[0] = BLUE;
color[1] = GREEN;
color[2] = DOG;

for(i = 0; i < 3; i++){ 
  if(color[i] == BLUE)
     printf("\nColor nr%d is blue", i);
}
moffeltje
  • 4,521
  • 4
  • 33
  • 57