ByVal call

ByVal call

am 08.02.2006 19:49:37 von Kamyk

Hello all!

I have a problem - some kind of theoretical problem.
What is the right call:
public function function_name (ByVal name1 as string) as string
or
public function function_name (name1 as string) as string

When should we use ByVal statement? Is it needed in the specifying a
function or procedure or when we have to write ByVal?

Thank you in advance for help
M.

Re: ByVal call

am 08.02.2006 20:10:38 von Randy Harris

The "right call" is entirely dependant upon what the intent of the function
is. When ByVal is used, only the value of the variable, not the variable
itself is passed into the function. The default behavior is ByRef. When
ByRef (or nothing) is specified a reference to the argument variables is
passed so if the variable is changed in the called procedure, it will also
be changed in the calling procedure.

Example

Sub SomeProcedure ()
numValue = 7
debug.print numValue
debug.print MyFunction numValue
debug.print numValue
End Sub

Function MyFunction (A as integer)
A = 2 * A
MyFunction = 2 * A
End Function

Above, when SomeProcedure is run, it calls MyFunction. Since the argument
is passed ByRef (the default) and is changed by the function, the change
would be seen in SomeProcedure. Before the function is called, the value is
7, after it is 14.

Basically if there is any possibility that a passed argument variable might
get changed in a procedure and the change is not desired in the calling
procedure then ByVal should be used.

Hope this helps.

BTW - personally, if I were creating the BASIC language - I would make ByVal
the default. Surprisingly, they never asked me.

--
Randy Harris
tech at promail dot com
I'm pretty sure I know everything that I can remember.


"news.onet.pl" wrote in message
news:dsdeg0$th8$1@news.onet.pl...
> Hello all!
>
> I have a problem - some kind of theoretical problem.
> What is the right call:
> public function function_name (ByVal name1 as string) as string
> or
> public function function_name (name1 as string) as string
>
> When should we use ByVal statement? Is it needed in the specifying a
> function or procedure or when we have to write ByVal?
>
> Thank you in advance for help
> M.
>
>