Why does a C/C++ compiler need know the size of an array at compile time? -
i know c standards preceding c99 (as c++) says size of array on stack must known @ compile time. why that? array on stack allocated @ run-time. why size matter in compile time? hope explain me compiler size @ compile time. thanks.
the example of such array is:
void func() { /*here "array" local variable on stack, space allocated *at run-time. why compiler need know size @ compile-time? */ int array[10]; }
to understand why variably-sized arrays more complicated implement, need know little how automatic storage duration ("local") variables implemented.
local variables tend stored on runtime stack. stack large array of memory, sequentially allocated local variables , single index pointing current "high water mark". index stack pointer.
when function entered, stack pointer moved in 1 direction allocate memory on stack local variables; when function exits, stack pointer moved in other direction, deallocate them.
this means actual location of local variables in memory defined reference value of stack pointer @ function entry1. code in function must access local variables via offset stack pointer. exact offsets used depend upon size of local variables.
now, when local variables have size fixed @ compile-time, these offsets stack pointer fixed - can coded directly instructions compiler emits. example, in function:
void foo(void) { int a; char b[10]; int c; a might accessed stack_pointer + 0, b might accessed stack_pointer + 4, , c might accessed stack_pointer + 14.
however, when introduce variably-sized array, these offsets can no longer computed @ compile-time; of them vary depending upon size array has on invocation of function. makes things more complicated compiler writers, because must write code accesses stack_pointer + n - , since n varies, must stored somewhere. means doing 2 accesses - 1 stack_pointer + <constant> load n, load or store actual local variable of interest.
1. in fact, "the value of stack pointer @ function entry" such useful value have around, has name of own - frame pointer - , many cpus provide separate register dedicated storing frame pointer. in practice, frame pointer location of local variables calculated, rather stack pointer itself.
Comments
Post a Comment