assign array with a local var???

Hi all,

I am just wondering is this (below code) valid in programming

   int xx = 10110;
   int i;
   long yy[] = {1,2,3,4,5,6,7,8,xx};

I compiled this using gcc will all working option successfully without getting any warning or error. I didn't see this kind of code in my past experience. Please comment the cons if any

Thanks and Regards...

I believe it conforms to C99, but not C89 - you'll get an error if you compile in 89 mode with the -pedantic flag.

I only see cons if you're going to port to a compiler that doesn't support this. Otherwise, you might as well take advantage of what the compiler can do for you to make your life easier.

1 Like

Thanks John, yes with -pedantic option it reporting following warnings

cc1: warnings being treated as errors
r.c: In function �main':
r.c:7: warning: initializer element is not computable at load time

surely this will creating issues at the time of porting

Not necessarily - it's valid C99 (I'm pretty sure...), so any compiler that supports that should have no problem with it.

I think if it's a const int that should be permissible, since that would make xx guaranteed computable not just load-time but compile-time...

Unfortunately not - in c89 initialisers must be constant expressions. A constant expression is one that only uses literal values and arithmetic operators, such as "2" or "3 * 2", not "3 * x", even if x is declared a const variable.

"const" does not mean "constant" - it merely means that the const variable itself cannot modify the memory at that address. Others can.

True for stack variables but not for static or global variables or literal strings, these frequently have hardware protection.

In any case that's besides the point. The compiler treats constant variables as constants, which was what I'd hoped would allow this assignment behavior. Oh well.

Yes, but the OP seems interested in standards conformance and whether another compiler would compile this code the same. It probably would thouch (especially in c99).