Specifies that a function result is returned by reference
Syntax
Description
Causes the function result to be returned by reference, rather than by value. A function returning ByRef will return the address of a variable, instead of making a copy like when returning by value. This allows the caller of the function to modify the variable which the function result points to.
If ByRef is not specified, the default is to return the function result by value.
Functions with ByRef result should not return local variables from the function, because they will be destroyed upon returning from the function, invalidating any pointer or reference to them. To help with writing safe code, the compiler will show an error message when a local variable is used with Function = x (or name = x) assignments and Return x statements.
Note: On the left-hand side of an assignment expression using the '=' symbol, the result of the function (returned by reference) must be enclosed in parentheses when the function calls one single argument, in order to solve the parsing ambiguity. From fbc version 0.90, '=>' can be used for assignments, in place of '=', same as for initializers, allowing to avoid parsing ambiguity (without parentheses). As for the arguments list, it should always be surrounded with parentheses even if empty.
Operators (member or global), when used as functions, have also the capability to return results by reference, by using the same syntax.
Example
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
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( )
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 be returned by reference, no copy will be created.
Function = _s
End Function
s = "abcd"
Print s
f1( ) &= "efgh"
Print s
'' At time of writing, the enclosing parentheses are required here.
( f2( s ) ) &= "ijkl"
Print s
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
Differences from QB
See also