Is there a way to change a local typed constant from * outside * that it declared?

Please note that this is just a thought experiment. I know that global (static) vars are bad, and breaking up is a bad idea anyway.

Consider the following code:

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

Assuming CanIBeChanged constants were included, how can I change the value of CanIBeChanged from outside the scope of the function that it declared?

PS no. I'm not going to ever use this code, it's just a question of interest.

+7
source share
1 answer

Well, this can only be done by leaking a pointer to a writable typed constant. Here is an example, which is a rather confusing way to print the beast number:

 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 locality region is limited by the function in which it is defined, the approach described above is the only possible solution.

+12
source

All Articles