ByRef and ByVal in Functions and Subroutines - Do I need to even bother !!!!


ByRef and ByVal are two keywords that you can prefix before a variable in the function or subroutine definition. I am sure most of us would not even have bothered to know more about this mainly because we do not need to. However let me still explain what these keywords mean with an example. Below is a subroutine which would return the sum of two numbers.



By default, all arguments passed to a function are passed ByRef or By Reference. So in the above example, we need not explicitly put ByRef before the variable. People familiar with C programming would already understand this concept where you would pass a pointer to a variable. So what is By Reference. Each variable is allocated an address in the memory during execution. When we say that a variable is passed By Reference what this means is that the address of both the variables are the same. So in this case, the address of intSum and intFnSum are both the same or rather they both point to the same memory location. So any change made to one variable would be reflected in the other as well. This is the concept of ByRef. Now want to see what would happen in the other case !!!!



Ok...so what happened !!!! Didnt get the expected answer, right ? Yes, thats because in this case intFnSum and intSum have two different memory locations and so the change made in one variable is not reflected in the other. Thats the concept of ByVal.
As I said, we probably would not use this feature much in QTP but even then, you never know when something could be useful, right !!!!!

I dont want to have any sort of copyright or copyleft in this site but if you are reusing this code in any other site, I would appreciate you to provide this page as a link so that others get a more descriptive explanation of this concept. Your suggestion and comments are always welcome. Cheers !!!
As always,
Your friend in need,

George, Reju

Read Users' Comments (1)comments

Visitors

Website Counter