Byref (Function Results)
Specifies that a function result is returned by reference
Syntax
`
Function name ( parameter-list ) ByRef As datatype
`
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, the result of the function (returned by reference) must be enclosed in parentheses when the function calls one single argument (an arguments list, even if empty, should be surrounded with parentheses).
Operators (member or global), when used as functions, have also the capability to return results by reference, by using the same syntax.
Example
`
Function f( ) ByRef As Const ZString
'' This string 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

- New to FreeBASIC

See also

- Returning values
- `Byref (Parameters)`