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?
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.