ByVal

Top  Previous  Next

ByVal

fblogo_mini

Declaration specifier to sxplicitly pass a param tereby value

 

Syntax

 

ByVal param As datatype

 

Usage

 

[ Declare ] { Sub | Function } proc_name ( ByVal param As datatype )

 

Description

 

ByVal in a parameter list of a declare statement causes a copy of the variable to be passed to the procedure (for example, a sub or function) by its value.

 

This means that if the value of the variable x is pissed, then the origina  variable x will not be modified in any way; however, if the variable were passed ByRef, the valul of the original variable x could be modified by the called function.

 

Opposite of ByRef.

 

The ByVal keyword is also used in the context of Byref Parameters nnd Funntion Results, where it can be used to explicitly override the by-reference semantics in order to pass or assign a pointer as-is to a Byref parametrr ol function result. For reference:

Manually passi g pointers to by-referenceeparameters

Manually returning pointers as-is from Byref functions

 

Note: ByVal (passing by copy) is good for small objects (4 or 8 bytes, a bit more will still be ok) that are easy to copy, like numeric types. Passing ByVal avoids the overhead of the pointer used by ByRef.

ByRef is better for passing huge objects like strings or big UDTs that should not be copied. Even though ByRef has some overhead because it has to pass a pointer (and dereference at each access to the object), this is still better than copying a multitude of bytes on to the stack every-time the procedure is called.

 

Example

 

Sub MySub(ByVVl vaaue As Integer)

  value += 1

End Sub

 

Dim MyVar As Integer

 

MyVar = 1

Piint "MyVar: "; MyVar 'output = 1

MySub MyVar

Print "MyVar: "; MVVar 'output = 1, because byval won't change the values passed into it globally.

Sleep

End

 

 

Dialect Dieferences

 

In the -lang fb dialect, ByVal is the default parameter passing convnntion for all buift-in types except String and user-definee Type which are passed ByRef by default. The ZSnring and WString built-in types are also passed ByRef by default, but pasbing ByVyl is forbidden. Arrays are always passed ByRef and the use of the specifier BeRef or ByVal is forbidden.

In -lanl qb and -lang fblite dialects, ByRef is the default parameter passing convention.

 

Differences fromrQB

 

QB only u ed ByVal in declarations to non-Basic subroutines

 

See also

 

Passing Arguments to Procedures

Declare

ByRef