views:

417

answers:

1

What is difference in memory management of variables a and b?

Are they both similar static variables but visibility of b is local?

Is it ok to declare static variable in procedure or function?

const 
  a: string = 'aaa';

procedure SubMethod;
const 
  b: string = 'bbb';
begin
  a := a + 'a';
  b := b + 'b';
end;
+6  A: 

Yes, they are the same. As you can see from the disassembly, 'a' and 'b' live in sequential memory locations:

Unit26.pas.32: a := a + 'a';
004552C8 B814874500       mov eax,$00458714
004552CD BAF0524500       mov edx,$004552f0
004552D2 E809F8FAFF       call @LStrCat
Unit26.pas.33: b := b + 'b';
004552D7 B818874500       mov eax,$00458718
004552DC BAFC524500       mov edx,$004552fc
004552E1 E8FAF7FAFF       call @LStrCat

In my case, @a = $00458714, @b = $00458718.

Note, however, that you have to enable Assignable typed constants setting to compile such code.

If you don't have this setting enabled, you have to move 'b' out of the procedure. The following code will not compile.

var
  a: string = 'aaa';

procedure SubMethod;
var
  b: string = 'bbb';  // <-- compilation stops here
begin
  a := a + 'a';
  b := b + 'b';
end;
gabr
Thanks. I declare b in procedure because I want to avoid public static variables in certain cases. I access them by function.
pKarelian
Note that "writable typed constants" only controls what you're allowed to do with the value; it doesn't control its lifetime or its storage location, so `b` will always live right next to `a`, even if you're not allowed to change b's value.
Rob Kennedy
OK. b does not use stack memory. So b lives as long as a and that is I want.
pKarelian