问题描述
在Delphi棱镜中,我们可以声明仅在特殊情况下才需要的变量。
In Delphi prism we can declare variables that is only needed in special occasions.
例如: 在棱镜中
eg: In prism
If acondition then
begin
var a :Integer;
end;
a := 3; //this line will produce error. because a will be created only when the condition is true
此处'a'不能分配3,因为它嵌套在一个分支内。
我们如何声明一个只能在delphi win32的分支内部使用的变量。因此,我可以减少内存使用量,因为只有在满足特定条件的情况下才会创建内存;
Here 'a' cannot be assigned with 3 because it is nested inside a branch.How can we declare a variable which can be used only inside a branch in delphi win32. So i can reduce memory usage as it is only created if a certain condition is true;
如果减少内存使用量不成问题,我们的缺点是什么(或者我们没有)
If reduced memory usage is not a problem what are the draw backs we have (or we don't have)
推荐答案
您的问题的前提是错误的。您假设在允许块级变量的语言中,当控件进入或离开这些变量的作用域时,程序会为这些变量分配和释放内存。因此,例如,您认为当 acondition
为true时,程序将调整堆栈以为 a
腾出空间。进入该块的变量。但是,您错了。
The premise of your question is faulty. You're assuming that in languages where block-level variables are allowed, the program allocates and releases memory for those variable when control enters or leaves those variables' scopes. So, for example, you think that when acondition
is true, the program adjusts the stack to make room for the a
variable as it enters that block. But you're wrong.
编译器会计算所有声明的变量和临时变量所需的最大空间,然后在进入函数时保留这些空间。分配空间就像调整堆栈指针一样简单。通常所需的时间与保留的空间量无关。底线是您的想法实际上不会节省任何空间。
Compilers calculate the maximum space required for all declared variables and temporary variables, and then they reserve that much space upon entry to the function. Allocating that space is as simple as adjusting the stack pointer; the time required usually has nothing to do with the amount of space being reserved. The bottom line is that your idea won't actually save any space.
具有块级变量的真正好处是它们的作用域是有限的。
The real advantage to having block-level variables is that their scopes are limited.
如果您确实需要某些变量仅在代码的一个分支中有效,则将其分解为一个单独的函数,然后将变量放在那里。
If you really need certain variables to be valid in only one branch of code, then factor that branch out to a separate function and put your variables there.
这篇关于在delphi中声明分支的块级变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!