BB___ByRef

=ByRef= toc

Description
> Causes the value of a variable that has been passed as a parameter to a sub or function to be returned with a new value if it has been changed in the sub or function.

> The ByRef reference is applied to the parameter in the definition of the sub or function.

> Passing by reference (ByRef) is only supported using string and numeric variables as parameters. (: will NOT work on array value)

> //If ByRef is not declared for a parameter, the value of the variable, passed as a parameter, will NOT change in the main program, regardless of how it might be changed in the sub or function.//

Syntax

 * 1) sub subName //byref var//
 * 2) function functionName(//byref var//)

Hints
> The default for passing parameters to subs and functions is "by value", which means the value does not change in the main program even if changed in the sub or function.

> Literal strings and numbers, or computed values as well as array values, may be passed ByRef, but their values will not come back from the sub or function.

Using ByRef in a sub
code format="lb" ' write a sub to make all letters in a sentence upper case: ' ask user to type sentence in all lower case print "Please type a sentence without using any capitals" input sentence$

' call the subroutine call capitalize sentence$

' back from the sub; sentence$ will now be all upper case letters: print "Here's the sentence in all capital letters:" print sentence$

wait end

' the subroutine with the parameter s$ representing the ' original variable, sentence$ ' declaring the variable ByRef instructs the sub to replace the ' original sentence$ with the string the sub creates.

sub capitalize byref s$ ' Here's where we make s$=s$ as modified by upper$ function. The ' upper$ function converts all characters to upper case. s$=upper$(s$) ' back to calling program end sub

code

Useful Functions
Swap sub (exchanging two values), by the model it exists in QBasic. Note: would not work for array items (JB byRef limitation) - so you cannot use it to bubble sort array.

code format="lb" 'example x = 1 : y = 2 print x, y         'Naturally prints 1 2 call swap x, y   print x, y          'Prints 2 1

' sub swap byRef x, byRef y   tmp = x    x = y    y = tmp end sub code