I get 'Variable x inaccessible here due to optimization'

Server Overflow picture Server Overflow · Jun 6, 2011 · Viewed 9.7k times · Source

I get 'Variable ForAllUsers inaccessible here due to optimization' even if the build configuration is set to 'Debug' and the Optimization is False. So, I cannot debug my program.

Why do I get this?
Which build is ran when I press the Run button?
How can I see


procedure Test(ForAllUsers: boolean);
VAR
   FName, Path1, Path2: string;
   RootKey: HKEY;
begin
 Result:= FALSE;
 TRY
  if ForAllUsers
  then
    begin
     RootKey:= HKEY_CLASSES_ROOT;
     Path1:= '';
     Path2:= '';
    end
  else
    begin
     RootKey:= HKEY_CURRENT_USER;           <----- Break point here
     Path1:= '\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\';
     Path2:= '\Software\Classes\';    
    end;

... end;


Update:
Only minutes since I posted this question, and it was already voted twice up and starred two times. Seems this is a pretty common issue.

Answer

David Heffernan picture David Heffernan · Jun 6, 2011

We all suffer from this from time to time. What I sometimes do is add some spurious code at the point at which I need to debug the variable that references the variable but does nothing. For example:

if x>0 then x := x*1;

Or if it is a boolean then:

if b then b := not not b;

Something along these lines is usually enough to get the compiler to write out code that keeps the variable alive so that the debugger can inspect it. Make sure you put the code right at the bottom of the routine! And make sure that you remember to remove it before checking the code in.