Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

how to avoid "initializer element is not constant"

6,171 views
Skip to first unread message

huamama

unread,
Oct 19, 2008, 10:58:05 PM10/19/08
to
hi,

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!

m_l_g3

unread,
Nov 1, 2008, 10:05:25 AM11/1/08
to
On Oct 20, 5:58 am, huamama <huam...@gmail.com> wrote:
> hi,
>
> 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;
#define b 20

sh.v...@gmail.com

unread,
Nov 2, 2008, 9:35:49 AM11/2/08
to


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

0 new messages