Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring block level variables for branches in delphi

Tags:

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

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)

like image 609
VibeeshanRC Avatar asked Nov 27 '22 14:11

VibeeshanRC


2 Answers

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.

like image 139
Rob Kennedy Avatar answered Dec 11 '22 00:12

Rob Kennedy


The concept of Local Variable Declaration Statements like in Java is not supported in Delphi, but you could declare a sub-procedure:

procedure foo(const acondition: boolean);

  procedure subFoo;
  var
    a: integer;
  begin
    a := 3;
  end;

begin
  If acondition then
  begin
    subFoo;
  end;
end;
like image 34
splash Avatar answered Dec 11 '22 01:12

splash