Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default value of 'Result' in Delphi?

Tags:

delphi

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))

like image 513
hansmaad Avatar asked Mar 17 '11 08:03

hansmaad


2 Answers

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?

like image 66
David Heffernan Avatar answered Oct 21 '22 23:10

David Heffernan


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

like image 21
splash Avatar answered Oct 21 '22 23:10

splash