In the following example:
int main(void) {
int a=7;
{
int a=8;
}
}
The generated assembly would be something like this (from Compiler Explorer) without optimizations:
main:
pushq %rbp
movq %rsp, %rbp
movl $7, -4(%rbp) // outer scope: int a=7
movl $8, -8(%rbp) // inner scope: int a=8
movl $0, %eax
popq %rbp
ret
How does the compiler know where the variable is if there are duplicately-named variables? That is, when in the inner scope, the memory address is at %rbp-8 and when in the outer scope the address is at %rbp-4.
There are many ways to implement the local scoping rule. Here is a simple example:
for ( introduces a new scope too for definitions in its first clause.extern forward declarations). Otherwise the symbol is added to the scope list.The above steps are performed for type and object names, a separate list of symbols is maintained for struct, union and enum tags.
Preprocessing is performed before all of this occurs, in a separate phase of program translation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With