Search code examples
delphiscopestatic-variables

Is there a way to change a local typed constant from *outside* the routine it's declared in?


Please note that this is just a thought experiment.
I know global (static) vars are bad and breaking scope is a bad idea in any case.

Consider the following code:

function IsItChanged: integer;
const
  CanIBeChanged: integer = 0;
begin
  Result:= CanIBeChanged; 
end;

Assuming writable constants have been enabled, how can I change the value of CanIBeChanged from outside the scope of the function it's declared in?

PS No I do not intend to ever use this code it's just a question out of interest.


Solution

  • Well, it can only be done by leaking a pointer to the writeable typed constant. Here is an example that takes a rather convoluted way to print the number of the beast:

    program NaughtyNaughtyVeryNaughty;{$J+}
    {$APPTYPE CONSOLE}
    procedure Test(out MyPrivatesExposed: PInteger);
    const
      I: Integer=665;
    begin
      MyPrivatesExposed := @I;
      inc(I);
    end;
    
    var
      I: PInteger;
    begin
      Test(I);
      Writeln(I^);
      Readln;
    end.
    

    Since the scope of a local is confined to the function in which it is defined, the approach outlined above is the only possible solution.