在循环中为局部变量分配空间 [英] Allocation of space for local variables in loops
问题描述
(是或否)在执行循环主体时分配在循环主体中声明的局部变量的空间,并在主体结束时释放.
(true or false) The space for a local variable that is declared in the body of the loop is allocated whenever the loop body is executed and deallocated when the body finishes.
这个问题的答案是错误的.但是为什么呢?
The answer to this question is false. But why?
推荐答案
该语句为false,因为未分配和释放局部变量空间.它存在于堆栈中,并在输入方法时保留.
The statement is false because local variable space is not allocated and deallocated. It exists on the stack and is reserved when the method is entered.
要查看如何使用堆栈空间,请使用以下代码编写一个小型测试程序:
To see how stack space is used, write a small test program with:
public static void test() {
{
int a = 1;
long b = 2;
int c = 3;
}
{
int x = 4;
int y = 5;
long z = 6;
}
}
现在,使用以下命令将其反汇编以查看字节码.
Now disassemble it with the following command to see the bytecode.
javap -c Test.class
这是输出.为了方便起见,我在右侧添加了Java代码.
Here is the output. I've added the Java code on the right for your convenience.
public static void test();
Code:
0: iconst_1 int a = 1;
1: istore_0
2: ldc2_w #22 long 2l long b = 2;
5: lstore_1
6: iconst_3 int c = 3;
7: istore_3
8: iconst_4 int x = 4;
9: istore_0
10: iconst_5 int y = 5;
11: istore_1
12: ldc2_w #24 long 6l long z = 6;
15: lstore_2
16: return return;
发生的事情是该方法保留了4个插槽". int
变量占用1个插槽,而 long
变量占用2个插槽.
What happens is that the method has reserved 4 "slots". An int
variable takes 1 slot, and a long
variable takes 2 slots.
所以代码确实说:
slot[0] = 1
slot[1-2] = 2L
slot[3] = 3
slot[0] = 4
slot[1] = 5
slot[2-3] = 6L
这显示了差异代码块中声明的局部变量如何重用插槽.
This shows how the slots are reused by local variables declared in difference code blocks.
这篇关于在循环中为局部变量分配空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!