何时为局部变量分配堆栈空间?堆栈、变量、局部、分配

2023-09-07 03:13:50 作者:闲棋

我对以下 C 代码有疑问:

I have a question about the following C code:

void my_function()
{
    int i1;
    int j1;

    // Do something...

    if (check_something())
    {
        int i2;
        int j2;

        // Do something else...
    }

    // Do some more stuff...
}

是否有关于何时为 i2 和 j2 分配/释放堆栈空间的保证,或者它是否取决于编译器?我希望堆栈指针在 i2 和 j2 进入范围时向下调整,并在它们超出范围时向上调整,但随后认为某些编译器可能只是优化"整个事情并在嵌套范围内考虑变量首先输入函数.

Are there any guarantees about when stack space is allocated/deallocated for i2 and j2 or does it depend on the compiler? I would expect the stack pointer to be adjusted down when i2 and j2 come into scope and adjusted back up when they go out of scope, but then thought some compilers may just "optimize" the whole thing and account for variables in a nested scope when the function is first entered.

我知道我可以查看编译器生成的汇编代码,但想知道是否可以将实现留给编译器.

I know I can look at the assembly code generated by my compiler, but was wondering if the implementation can be left up to the compiler.

谢谢!

推荐答案

编译器可以为所欲为,只要语言的语义是保留>.换句话说,i2j2 可以在执行到达其块的入口点之前绑定到内存位置,并且可以在任何时候不受限制,只要不这样做't 影响代码的语义.

The compiler is free to do whatever it wants, as long as the semantics of the language are reserved. In other words, i2 and j2 can be bound to memory places before the execution reaches the entry point of their block, and can be unbounded any time as long as that doesn't affect the semantics of your code.