# Thread: can't we pass array by reference?

1. ## can\'t we pass array by reference?

Function f(byref arr)
arr(0)=2
End Function

Dim a(1)
a(0)=1
a(1)=2

f(a)
msgbox a(0) 'displays original 1

3. ## Re: can\'t we pass array by reference?

try using the below code:

Function f(byref arr)
arr(0)=2
End Function

Dim a(1)
a(0)=1
a(1)=2

f a ' or use call f(a)
msgbox a(0)

4. ## Re: can\'t we pass array by reference?

a better way to declare array

Dim a:a=Array(1,2)

5. ## Re: can\'t we pass array by reference?

Vijay
well it worked but very strange behavior when called with parenthesis.It should have thrown error in my script

6. ## Re: can\'t we pass array by reference?

When you pass any parameter to a function with parenthesis around it, no matter how the parameter is defined(ByVal/ByRef) in the functions, it is considerd as ByValue

for example
f(a)
x = f ((a))
x = f((a), b)

In all the above cases a is passed by Value even though it is defined ByRef in function

7. ## Re: can\'t we pass array by reference?

Kashi_Vishwanath,
That's a very good observation.
Thanks

8. ## Re: can\'t we pass array by reference?

Hello,
when using parenthises you need to use the keyword Call

here is an example :

'Code 1: using Call keyword
Function f(byref arr)
arr(0)=2
End Function

Dim a(1)
a(0)=1
a(1)=2

call f (a) 'using Call
msgbox a(0) ' result=2

f a ' no parenthesis result=2
msgbox a(0)

'Code 2: without using Call keyword
Function f(byref arr)
arr(0)=2
End Function

Dim a(1)
a(0)=1
a(1)=2

f (a) 'using Parenthesis without call keyword
msgbox a(0) ' result=1

f a ' or use call f(a)
msgbox a(0) 'no Parenthesis, no call keyword result =2

9. ## Re: can\'t we pass array by reference?

Good point vishwanath [img]/images/graemlins/smile.gif[/img]

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•

vBulletin Optimisation provided by vB Optimise v2.6.0 Beta 4 (Pro) - vBulletin Mods & Addons Copyright © 2016 DragonByte Technologies Ltd.