Skip to content

BYREF(函数返回值)


指定函数结果按引用返回

语法

Function name ( parameter-list ) Byref As datatype

说明

使函数结果按引用返回,而非按值返回。返回 Byref 的函数将返回变量的地址,而不是像按值返回时那样创建副本。这允许函数的调用者修改函数结果所指向的变量。

如果未指定 Byref,默认按值返回函数结果。

具有 Byref 返回值的函数不应返回函数内的局部变量,因为它们在函数返回时会被销毁,导致任何指向它们的指针或引用无效。为了帮助编写安全代码,当局部变量用于 Function = x(或 name = x)赋值和 Return x 语句时,编译器会显示错误信息。

注意:在使用 = 符号的赋值表达式左侧,当函数(按引用返回)只调用一个参数时,函数结果必须用括号括起来,以消除解析歧义。可以使用 => 代替 = 进行赋值,与初始化器相同,从而避免解析歧义(无需括号)。对于参数列表,即使为空也应始终用括号括起来。

运算符(成员或全局)在用作函数时,也能够使用相同的语法按引用返回结果。

示例

start GeSHi

vb
Function min( ByRef I As Integer , ByRef J As Integer ) ByRef As Integer
    '' The smallest integer will be returned by reference, no copy will be created.
    If I < J Then
        Return I
    Else
        Return J
    End If
End Function

Dim As Integer A = 13, B = 7
Print A, B
Print min( A , B )
min( A , B ) = 0
Print A, B

end GeSHi

start GeSHi

vb
Function f( ) ByRef As Const ZString
    '' This string literal (because statically allocated in memory) will be returned by reference, no copy will be created.
    Function = "abcd"
End Function

Print f( )

end GeSHi

start GeSHi

vb
Dim Shared As String s

Function f1( ) ByRef As String
   '' This variable-length string will be returned by reference, no copy will be created.
   Function = s
End Function

Function f2( ByRef _s As String ) ByRef As String
   '' This variable-length string will transit by reference (input and output), no copy will be created.
   Function = _s
End Function

s = "abcd"
Print s

f1( ) = f1( ) & "efgh"
Print s

'' The enclosing parentheses are required here on the left-hand side.
( f2( s ) ) = f2( s ) & "ijkl"
Print s

'' The enclosing parentheses are not required here on the left-hand side.
f2( s ) => f2( s ) & "mnop"
Print s

end GeSHi

start GeSHi

vb
Function power2( ByRef _I As Integer ) ByRef As Integer
   _I *= _I
   '' This integer will be returned by reference, no copy will be created.
   Function = _I
End Function

Dim As Integer I = 2
power2( power2( power2( I ) ) )  '' Function return-byref cascading is equivalent to ((I*I)*(I*I))*((I*I)*(I*I)) = I^8
Print I

end GeSHi

与 QB 的差异

  • FreeBASIC 新增特性

另请参阅

返回 目录

基于 FreeBASIC 官方文档翻译 如有侵权请联系我们删除
FreeBASIC 是开源项目,与微软公司无隶属关系