I want to initialize an array in my codes. When I tried to compiled
it, it shows "initializer element is not constant" error, but I tied
to use const variable, this error still remains.
Is there any way to use const variable to avoid this error?
my codes is below:
int a = 10;
static const int b = 20;
const int c = 20;
int p[] = {a, b, c};
int main()
{
printf("hello");
return 0;
}
Thanks!
In my opinion, when doing aggregate initialization, values have to be
compile time constant. i.e. constant strings like "hello world" or
numeral constants like 10,20 etc.
one probable reason I believe for not doing the constant folding by
compiler here is that it handles one translation unit (file) at a time
and tomorrow you could also say the following in your case.
/* file main.c */
extern int x;
int a = 10;
static const int b = 20;
const int c = x;
int p[] = {a, b, c};
int main()
{
printf("hello");
return 0;
}
In this case, compiler will not be able to know the value by which to
initialize the p[2].
on the side note, This group is mainly for queries related to gcc
compiler. you should put this query on comp.lang.c their you might
additional help.
-- vIpIn