问题描述
函数的 Result 变量是否有任何保证的默认值,如0,'或nil?或者结果始终在使用前被初始化?
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;
它工作正常,但是现在我收到一些包含以前调用该函数的内容的字符串。当我在开始添加一个 Result:=''
的时候,这样可以。什么时候应该初始化 Result
变量,何时不需要? (string,primitives,Class instance(nil))
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))
推荐答案
类型为 / code>实际上被编译器视为一个隐式var参数。当函数开始执行时,
Result
变量包含随后将分配返回值的局部变量中的任何值。
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 initialise function return values. This advice holds not only for strings, but for all data types.
此问题仅在昨天在。
这篇关于Delphi中“Result”的默认值是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!