在 C 中,大括号是否充当堆栈框架? [英] In C, do braces act as a stack frame?

查看:24
本文介绍了在 C 中,大括号是否充当堆栈框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在一组新的大括号内创建一个变量,该变量是从右大括号的堆栈中弹出,还是一直挂到函数结束?例如:

If I create a variable within a new set of curly braces, is that variable popped off the stack on the closing brace, or does it hang out until the end of the function? For example:

void foo() {
   int c[100];
   {
       int d[200];
   }
   //code that takes a while
   return;
}

d 会在 需要一段时间的代码 部分占用内存吗?

Will d be taking up memory during the code that takes a while section?

推荐答案

不,大括号不充当堆栈框架.在 C 中,大括号只表示命名范围,但当控制权离开堆栈时,没有任何东西被销毁,也没有任何东西从堆栈中弹出.

No, braces do not act as a stack frame. In C, braces only denote a naming scope, but nothing gets destroyed nor is anything popped off the stack when control passes out of it.

作为编写代码的程序员,您经常可以将其视为堆栈帧.大括号内声明的标识符只能在大括号内访问,因此从程序员的角度来看,它们就像在声明时被压入堆栈,然后在退出作用域时弹出.但是,编译器不必生成在进入/退出时推送/弹出任何内容的代码(通常他们不需要).

As a programmer writing code, you can often think of it as if it is a stack frame. The identifiers declared within the braces are only accessible within the braces, so from a programmer's point of view, it is like they are pushed onto the stack as they are declared and then popped when the scope is exited. However, compilers don't have to generate code that pushes/pops anything on entry/exit (and generally, they don't).

另请注意,局部变量可能根本不使用任何堆栈空间:它们可以保存在 CPU 寄存器或其他一些辅助存储位置中,或者完全被优化掉.

Also note that local variables may not use any stack space at all: they could be held in CPU registers or in some other auxiliary storage location, or be optimized away entirely.

因此,d 数组理论上可以为整个函数消耗内存.但是,编译器可能会将其优化掉,或者与其他使用生命周期不重叠的局部变量共享其内存.

So, the d array, in theory, could consume memory for the entire function. However, the compiler may optimize it away, or share its memory with other local variables whose usage lifetimes do not overlap.

这篇关于在 C 中,大括号是否充当堆栈框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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