sam*_*249 2 c compiler-construction assembly scope
In the following example:
int main(void) {
int a=7;
{
int a=8;
}
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
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.
有很多方法可以实现局部作用域规则。这是一个简单的例子:
for (在第一个子句中也为定义引入了一个新的范围。extern前向声明除外)。否则,该符号将添加到范围列表中。上述步骤的类型和对象名称进行的,符号的一个单独的列表被维持struct,union和enum标记。
在所有这些发生之前,在程序翻译的单独阶段执行预处理。