Revision [16674]

This is an old revision of KeyPgByrefFunction made by FxMwikki on 2013-03-23 18:05:40.

 

BYREF (function results)


Specifies that a function result is returned by reference

Syntax:
KeyPgFunction Function name ( parameter-list ) Byref KeyPgAs As DataType 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.

Examples:
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:
See also:
Back to Procedures
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki



sf.net phatcode