Is there any guaranteed default value for the Result variable of a function, like 0, '' or nil? Or should Result always be initialised before use?
I have a function returning a string like this:
function Foo(): String
begin
while {...} do
Result := Result + 'boingbumtschak';
end;
It worked fine, but now I get some strings containing contents from a previous call to the function. When I add a Result := ''
at the beginning, it is OK. When should I initialize the Result
variable and when don't I have to? (strings, primitives, Class instances (nil))
A function return value of type string
is actually treated by the compiler as an implicit var parameter. When the function begins execution, the Result
variable contains whatever is in the local variable to which the return value will subsequently be assigned.
Accordingly, you should always initialize function return values. This advice holds not only for strings, but for all data types.
This issue was discussed just yesterday here on Stack Overflow:
Do I need to setLength a dynamic array on initialization?
If the function exits without assigning a value to Result or the function name, then the function's return value is undefined.
see Delphi Reference > Procedures and Functions > Function Declarations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With