Data Flow Revisited

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

1. Create random number (Out Random Number)
2. Do
3. Get user choice (Out User’s Guess)
4. Check users choice (In User’s Guess, In Random Number)
5. loop until random number found
6. 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