Suppose I have the following code:
function DoSomething:Boolean;
var obj : TMyObject;
i : Integer;
begin
Result := False; //We haven't executed GetValue() correctly yet
obj := TMyObject.Create();
try
//perform some code that may produce an exception
i := obj.GetValue();
//Set the return to True as we executed GetValue() successfully
Result := True;
finally
//do some cleanup
obj.Free;
end;
end;
The Delphi compiler is complaining that the value assigned to Result is never used in the first line.
I'm probably missing something obvious, but i don't see why the compiler would optimize this out (if optimization's are on).
I have always been taught to explicitly set my variables so as no confusion what their values are. On top of that, should the GetValue()
function generate an exception, the Result := True;
line will never execute. So we are at the mercy of whatever Delphi initialized the variable to be.
So is this safe/acceptable code? Should i simply remove the first line of the method, which would make it a lot harder to read? Failing that I would have to turn the specific compiler warning off, but I'm reluctant to do that as this warning message can give useful information.
Result
if you don't initialize it, the answer is nothing. See Is Result variable defined from first line in a function?. – LU RD