何时为局部变量分配堆栈空间? [英] When is stack space allocated for local variables?

查看:18
本文介绍了何时为局部变量分配堆栈空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下 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.

这篇关于何时为局部变量分配堆栈空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆