<p>I copied some Delphi code from one project to another, and found that it doesn't compile in the new project, though it did in the old one. The code looks something like this:</p>

<pre><code>procedure TForm1.CalculateGP(..)
const
   Price : money = 0;
begin
   ...
   Price := 1.0;
   ...
end;
</code></pre>

<p>So in the new project, Delphi complains that "left side cannot be assigned to" - understandable! But this code compiles in the old project. So my question is, <strong>why</strong>? Is there a compiler switch to allow consts to be reassigned? How does that even work? I thought consts were replaced by their values at compile time?</p>

[{'answer_id': 48938, 'author': 'Ray', 'author_id': 233, 'author_profile': 'https://Stackoverflow.com/users/233', 'pm_score': 6, 'selected': True, 'text': "<p>You need to turn assignable typed constants on.\n\nProject -> Options -> Compiler -> Assignable typed Constants</p>\n\n<p>Also you can add <code>{$J+}</code> or <code>{$WRITEABLECONST ON}</code> to the pas file, which is probably better, since it'll work even if you move the file to another project.</p>\n"}, {'answer_id': 49060, 'author': 'Barry Kelly', 'author_id': 3712, 'author_profile': 'https://Stackoverflow.com/users/3712', 'pm_score': 5, 'selected': False, 'text': '<p>Type-inferred constants can only be scalar values - i.e. things like integers, doubles, etc. For these kinds of constants, the compiler does indeed replace the constant\'s symbol with the constant\'s value whenever it meets them in expressions.</p>\n\n<p>Typed constants, on the other hand, can be structured values - arrays and records. These guys need actual storage in the executable - i.e. they need to have storage allocated for them such that, when the OS loads the executable, the value of the typed constant is physically contained at some location in memory.</p>\n\n<p>To explain why, historically, typed constants in early Delphi and its predecessor, Turbo Pascal, are writable (and thus essentially initialized global variables), we need to go back to the days of DOS.</p>\n\n<p>DOS runs in real-mode, in x86 terms. This means that programs have direct access to physical memory without any <a href="http://en.wikipedia.org/wiki/Memory_management_unit" rel="noreferrer">MMU</a> doing virtual-physical mappings. When programs have direct access to memory, no memory protection is in effect. In other words, if there is memory at any given address, it is both readable and writable in real-mode.</p>\n\n<p>So, in a Turbo Pascal program for DOS with a typed constant, whose value is allocated at an address in memory at runtime, that typed constant will be writable. There is no hardware MMU getting in the way and preventing the program from writing to it. Similarly, because Pascal has no notion of \'const\'ness that C++ has, there is nothing in the type system to stop you. A lot of people took advantage of this, since Turbo Pascal and Delphi did not at that time have initialized global variables as a feature.</p>\n\n<p>Moving on to Windows, there is a layer between memory addresses and physical addresses: the memory management unit. This chip takes the page index (a shifted mask) of the memory address you\'re trying to access, and looks up the attributes of this page in its <a href="http://en.wikipedia.org/wiki/Page_table" rel="noreferrer">page table</a>. These attributes include readable, writable, and for modern x86 chips, non-executable flags. With this support, it\'s possible to mark sections of the .EXE or .DLL with attributes such that when the Windows loader loads the executable image into memory, it assigns appropriate page attributes for memory pages that map to disk pages within these sections.</p>\n\n<p>When the 32-bit Windows version of the Delphi compiler came around, it thus made sense to make const-like things <strong>really</strong> const, as the OS also has this feature.</p>\n'}, {'answer_id': 68314, 'author': 'Francesca', 'author_id': 9842, 'author_profile': 'https://Stackoverflow.com/users/9842', 'pm_score': 4, 'selected': False, 'text': '<ol>\n<li><p>Why: Because in previous versions of Delphi the typed constants were assignable by default to preserve compatibility with older versions where they were always writable (Delphi 1 up to early Pascal).<br>\nThe default has now been changed to make constants really constant…</p></li>\n<li><p>Compiler switch: {$J+} or {$J-} {$WRITEABLECONST ON} or {$WRITEABLECONST OFF}<br>\nOr in the project options for the compiler: check assignable typed Constants  </p></li>\n<li>How it works: If the compiler can compute the value at compile time, it replaces the const by its value everywhere in the code, otherwise it holds a pointer to a memory area holding the value, which can be made writeable or not.  </li>\n<li>see 3.</li>\n</ol>\n'}, {'answer_id': 100061, 'author': 'PatrickvL', 'author_id': 12170, 'author_profile': 'https://Stackoverflow.com/users/12170', 'pm_score': 2, 'selected': False, 'text': "<p>Like Barry said, people took advantage of consts; One of the ways this was used, was for keeping track of singleton instances.\nIf you look at a classic singleton implementation, you would see this :</p>\n\n<pre><code>  // Example implementation of the Singleton pattern.\n  TSingleton = class(TObject)\n  protected\n    constructor CreateInstance; virtual;\n    class function AccessInstance(Request: Integer): TSingleton;\n  public\n    constructor Create; virtual;\n    destructor Destroy; override;\n    class function Instance: TSingleton;\n    class procedure ReleaseInstance;\n  end;\n\nconstructor TSingleton.Create;\nbegin\n  inherited Create;\n\n  raise Exception.CreateFmt('Access class %s through Instance only', [ClassName]);\nend;\n\nconstructor TSingleton.CreateInstance;\nbegin\n  inherited Create;\n\n  // Do whatever you would normally place in Create, here.\nend;\n\ndestructor TSingleton.Destroy;\nbegin\n  // Do normal destruction here\n\n  if AccessInstance(0) = Self then\n    AccessInstance(2);\n\n  inherited Destroy;\nend;\n\n{$WRITEABLECONST ON}\nclass function TSingleton.AccessInstance(Request: Integer): TSingleton;\nconst\n  FInstance: TSingleton = nil;\nbegin\n  case Request of\n    0 : ;\n    1 : if not Assigned(FInstance) then\n          FInstance := CreateInstance;\n    2 : FInstance := nil;\n  else\n    raise Exception.CreateFmt('Illegal request %d in AccessInstance', [Request]);\n  end;\n  Result := FInstance;\nend;\n{$IFNDEF WRITEABLECONST_ON}\n  {$WRITEABLECONST OFF}\n{$ENDIF}\n\nclass function TSingleton.Instance: TSingleton;\nbegin\n  Result := AccessInstance(1);\nend;\n\nclass procedure TSingleton.ReleaseInstance;\nbegin\n  AccessInstance(0).Free;\nend;\n</code></pre>\n"}]
['https://Stackoverflow.com/questions/48934', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/369/']