2

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;
5
  • What Delphi version are you using? The above code can't be compiled in Delphi 2009 because constants can't be changed. Commented Jan 30, 2010 at 14:53
  • 3
    Serg: D4+ versions need $J+ iirc, but it still works. Commented Jan 30, 2010 at 15:03
  • 2
    Yes, {$J+} = {$WRITEABLECONST ON}. The feature is called "Writeable typed constants" in Delphi help - not easy to find if you forgot about {$J+} :) Commented Jan 30, 2010 at 15:21
  • I am using Delphi 2007 and Delphi 2010 and writeable typed constants are allowed. Commented Jan 30, 2010 at 15:36
  • @Serg: Actually there's an option for it in Project -> Options, so it's not that hard to find. Commented Jan 30, 2010 at 15:57

1 Answer 1

7

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I declare b in procedure because I want to avoid public static variables in certain cases. I access them by function.
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.
OK. b does not use stack memory. So b lives as long as a and that is I want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.