Initializing a normal array through a non-constant variable

Apr 1, 2009 at 3:01am
My teacher keeps insisting that this will work.

1
2
int number = 10;
int myarray[number];


Indeed this does compile and run on the ten year old compiler that we have to use, but I am almost certain that this should not work.

I have tested this in VC++ and it doesn't work. I already knew it wouldn't work but just to be sure I tested it.

Please correct me if I'm wrong, but the above code shouldn't work because the array is being declared with a non-constant value. Is this just a fluke that comes with the 10 year old compiler?
Last edited on Apr 1, 2009 at 3:01am
Apr 1, 2009 at 3:04am
It seems to work in gcc as well, which actually blows my mind because I thought it was illegal as well.

Very interesting. Perhaps it's legal in C++ but illegal in C? I don't know either. I'm interested in an answer to this question as well.
Apr 1, 2009 at 5:31am
It is illegal under strict ISO standards compliance.

MingW will let you do it if you turn off ISO compliance.

I'm not sure if MSVC 2008 will let you do it at all (I couldn't find the option for turing off ISO standards compliance).
Apr 1, 2009 at 5:37am
NEVER DO THIS!!!!!
Apr 1, 2009 at 3:57pm
@eker676: what compiler are you using? Have you checked the options to determine what level of std compliance it is set to?
Apr 1, 2009 at 4:24pm
Is better compiling standard C++ as the standards are always valid
Apr 1, 2009 at 4:28pm
purely illegal.

1
2
3
int number = 10;
int myarray[number];
number = 100;


if you do this what will happen.
Apr 1, 2009 at 6:50pm
GCC provides this as an extension as Disch said, and as guestgulkan said it is not in the Standard.

It is easy for compilers to implement this functionality. The declaration

int x;

causes the compiler to allocate sizeof( int ) bytes of stack space (of course the value is known at compile time, so the compiler generates, for example,

sub %esp, 4

But the above example, number is not known at compile time, so code is generated to read the value of the variable from memory and then sub the stack pointer using that.
For example,

; assume %ebp = %esp at this point for simplicity
sub $4, %esp ; allocate space for number
mov $0a, 4(%ebp) ; number = 10;
mov 4(%ebp), %eax ; put number in EAX
shl $4, %eax ; EAX *= 4 since we're allocating "number" ints (sizeof int = 4)
sub %eax, %esp ; Allocate stack space for myarray

At this point, if necessary, the compiler can store the size of the array on the stack also so it knows how many bytes to "pop" off the stack when the array goes out of scope.
Apr 1, 2009 at 7:01pm
I told her that it wasn't standard and declared a dynamic array instead.
Topic archived. No new replies allowed.