Given the following code where the return value is not set, what is returned?
Function MyFunction : Integer;
begin
end;
Given the following code where the return value is not set, what is returned?
Function MyFunction : Integer;
begin
end;
The returned value is undefined; it can be anything.
Hence, this is a bug.1, 2
In fact, the compiler warns you about it:
[dcc32 Warning]: W1035 Return value of function 'MyFunction' might be undefined.
1 I thought this was obvious, but clearly not: I mean that it is a bug when a function doesn't set the Result
variable. So, if a Delphi programmer writes a function that, under some conditions, fails to assign a value to Result
, then that programmer has made a mistake and should fix it ASAP. I did not mean that there is a bug in the Delphi language or the Delphi compiler.
2 Well, it doesn't have to be a bug, but almost always it is - at least in sane code. The exception would be if the contract of the function explicitly says that the returned value is undefined under some specific and testable condition. For instance, we all know about the TryXToY
idiom, like TryStrToInt(const S: string; out Val: Integer): Boolean
. If the conversion is possible, the function returns True
and Val
is assigned. If not, the function returns False
and Val
might well be left undefined. You could, in theory, write a function with the opposite behaviour, where the "definedness" of the result is given by an out
parameter. That, however, would be very counter-intuitive to most programmers, so it would be a bad idea.