Initializing a normal array through a non-constant variable

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
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.
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).
NEVER DO THIS!!!!!
@eker676: what compiler are you using? Have you checked the options to determine what level of std compliance it is set to?
Is better compiling standard C++ as the standards are always valid
purely illegal.

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


if you do this what will happen.
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.
I told her that it wasn't standard and declared a dynamic array instead.
Topic archived. No new replies allowed.