I have had a lot of questions about ByVal and ByRef so I thought I would clear it up in a quick posting.WARNING my quick postings have been known to take a while 🙂
Lets look at a standard grade program you created and present it in a more “Higher” fashion. The “Guess Number” program was used in the old Standard Grade course, it asked the user to think of a number and then displayed if the number was bigger or smaller than a random number it had created until the user guessed the right number.
The Pseudocode went something like this
- Create random number (Out Random Number)
- Do
- Get user choice (Out User’s Guess)
- Check users choice (In User’s Guess, In Random Number)
- loop until random number found
- display message
As always the first thing to do is to create the top level of the program
As you can see I have added procedures and parameters that  might have been missing when you did it in standard grade.
Here is the Make Random procedure
Notice that it uses ByRef, this is because the value of the parameter needs to be changed within the procedure.
For the Get Guess procedure I decided to bring in some validation, I wanted a whole number that is between 1 and 20. I have not checked for strings so these would still present a challenge.
Notice that I use a conditional loop to keep asking for the number and a boolean variable to tell the loop when I have a valid number. The nested IF’s allow the data to be checked sequentially. I could have put a more complex condition with one IF statement, however, this would not have let you see one check at a time. The number is passed ByRef as it needs to be changed within the procedure.
For Check Guess you will notice I change the actual and formal parameter (TBH I have done that for all procedures – check back if you don’t believe me)
The parameters are passed ByVal as I do not want this procedure to change their contents.
Take a little time and look back at the program, you should now see how the flow of data in the pseudocode is mirrored in the ByVal and ByRef.
- ByRef = Out = Data can be changed
- ByVal = In = Data does not change