Let us say I have an array
int aVar[10];
...
...
for(i=0; i<10; i++)
aVar[i] = i*10;
Here, what I know is that the array is referenced as a pointer and the location of the indexed value is calculated with something like: (base address of aVar) + sizeof(int) * i. Please correct me if I’m wrong.
My questions:
Is this calculation already done by the compiler before running the executable, or this arithmetic calculation of finding exact location in the array done while executing?
Of course, we can not get the address of aVar at the compile time.
Nominally it is done at runtime, but the standard doesn’t care provided that the result is correct (the standard calls this the “as-if” rule). It’s up to whoever wrote your C implementation, and it might depend what optimization options you use.
If the compiler unrolls the loop then it would know the offset of
aVar[0],aVar[1]etc from the stack pointer, the same as it knows the offset ofaVarfrom the stack pointer. So there’s no unavoidable obstacle to the code looking something like: