Chapter 6 Procedures and Functions Instructor Bindra Shrestha
Chapter 6 Procedures and Functions Instructor: Bindra Shrestha University of Houston – Clear Lake CSCI 3131. 01
Acknowledgement Dr. Xinhua Chen And Starting Out with Visual Basic 2010 by Tony Gaddis and Kip Irvine
Topics • • Procedures Passing arguments to Procedures Functions Debugging: • Step into, over, and out of procedures and functions
Introduction • A procedure is a collection of statements that performs a task – Event handlers are a type of procedure • A function is a collection of statements that performs a task and returns a value to the VB statement that executed it – Functions work like intrinsic functions, such as CInt and Is. Numeric • A method can be either a procedure or a function
Procedures A moderately complex program needs to perform multiple tasks. A procedure is a block of program code that performs a specific task. A program can be considered as the assembly of multiple procedures. Execution of a procedure is commonly referred to as calling a procedure. Most Visual Basic procedures are Sub procedures and Function procedures.
How Procedure Works A (called) procedure is invoked by another procedure (caller). The called procedure does the job and return the result to the caller or simply transfer control to the caller without returning anything. An analogy of procedure calls: boss worker 1 worker 4 worker 2 worker 5 worker 3
Sub Procedures vs. Function Procedures A Sub procedure does not return a value after performing its assigned task. A Function procedure returns a value after performing its assigned task. A Function procedure can only return one value.
Sub Procedures Two types of Sub procedures: 1. Event procedures - Associated with a specific object and event 2. General Purpose Sub procedures - Independent of any object and event; can be called (or invoked) from one or more places in an application.
Sample Procedure, Tutorial 6 -1 Private Sub btn. Go_Click(By. Val sender As System. Object, _ By. Val e As System. Event. Args) Handles btn. Go. Click ' This procedure calls the Display. Message procedure. lst. Output. Items. Add("Hello from btn. Go_Click procedure. ") lst. Output. Items. Add("Now I am calling the " & _ "Display. Message procedure. " "procedure. ") Display. Message() lst. Output. Items. Add("Now I am back " _ & "in the btn. Go_Click procedure. ") End Sub Returns to btn. Go_Click Calls Display. Message procedure Sub Display. Message() 'A Sub procedure that displays a message. lst. Output. Items. Add("") lst. Output. Items. Add("Hello from Display. Message procedure. ") lst. Output. Items. Add("") End Sub
Declaring a Procedure [Access. Specifier] Sub Procedure. Name ([Parameter. List]) [Statements] End Sub • Access. Specifier is optional and establishes accessibility to the program • Sub and End are keywords • Procedure. Name used to refer to procedure – Use Pascal casing, capitalize 1 st character of the name and each new word in the name • Parameter. List is a list of variables or values being passed to the sub procedure. It is optional.
More on the Access Specifier • • Private allows use only from that form Public allows use from other forms If not specified, default is Public There are other access specifiers such as: – Protected – Friend – Protected Friend – These will be discussed in later chapters
Placing Sub Procedure in File General Purpose Sub procedures can be placed anywhere in the Form's code module. Likewise, the event procedures can also be placed anywhere in the Form's code module.
Sample Procedure Private Sub Display. Grade() ' Display the int. Average score. lbl. Average. Text = int. Average. To. String() ' Determine and display the letter grade. Select Case int. Average Case 90 To 100 lbl. Letter. Grade. Text = "A" Case 80 To 90 lbl. Letter. Grade. Text = "B" Case 70 To 79 lbl. Letter. Grade. Text = "C" Case 60 To 69 lbl. Letter. Grade. Text = "D" Case Else lbl. Letter. Grade. Text = "E" End Select End Sub
Procedures and Static Variables • Variables needed only in a procedure, should be declared within that procedure – Creates a local variable with scope only within the procedure where declared – Local variable values are not saved from one procedure call to the next • To save value between procedure calls, use Static keyword to create a static local variable – Static Variable. Name As Data. Type – Scope is still only within the procedure – But variable exists for lifetime of application
Arguments • Argument – a value passed to a procedure • We’ve already done this with functions – Value = CInt(txt. Input. Text) – Calls the CInt function and passes txt. Input. Text as an argument • A procedure must be declared with a parameter list in order to accept an argument
Passing Multiple Arguments Show. Sum(int. Value 1, int. Value 2) ' calls Show. Sum procedure Sub Show. Sum(By. Val int. Num 1 As Integer, _ By. Val int. Num 2 As Integer) ' This procedure accepts two arguments, and prints ' their sum on the form. Dim int. Sum As Integer int. Sum = int. Num 1 + int. Num 2 Message. Box. Show("The sum is " & int. Sum. To. String) End Sub • Multiple arguments separated by commas • Value of first argument is copied to first • Second to second, etc.
Passing Variables A variable has both a value and a unique address in the computer's memory. Either the value or the address can be passed to a Sub procedure. Two ways of passing parameters: (1) Pass by value. The value of the variable is passed to the called procedure; (2) Pass by reference: The address of the variable is passed to the called procedure.
Two analogies Telling someone the balance of your banking account passes the information about your banking account. This is equivalent to "pass by value". Giving someone the information on the account number, PIN, etc. authorizes the person to deposit or withdraw from the account, as well as to query the balance. This equivalent to "pass by reference".
Pass Variables by Value Passing variables by value is specified in the parameter list. Use the keyword By. Val in the variable declaration. When the procedure is invoked, only the value of the variable is passed to the procedure. Example: Private Sub Display. Message(By. Val pet As String, By. Val years As String) message. Label. Text = "Your pet " & pet & " is " _ & years & " years old. " End Sub
Pass Variables by Value (Cont'd) In the calling procedure, you may have code like this: Private Sub get. Info. Button_Click(By. Val sender As Object, _ By. Val e As System. Event. Args) Handles get. Info. Button. Click Dim pet. Name As String Dim pet. Age As String pet. Name = Input. Box("Pet's name: ", "Name Entry") pet. Age = Input. Box("Pet's age (years): ", "Age Entry") Display. Message(pet. Name, pet. Age) End Sub
Passing Variables by Reference • Passing variables by reference gives the receiving procedure access to the variable being passed. • In most cases, you pass variables by reference when you want the receiving procedure to change the contents of the variables. • Use the By. Ref keyword in the parameter list.
Passing Variables by Reference (Cont'd) Example Private Sub calc. Button_Click(By. Val sender As Object, _ By. Val e As System. Event. Args) Handles calc. Button. Click Dim hours. Wkd As Decimal Dim rate. Of. Pay As Decimal Dim gross. Pay As Decimal hours. Wkd = Convert. To. Decimal(hours. List. Box. Selected. Item) rate. Of. Pay = Convert. To. Decimal(rate. List. Box. Selected. Item) Calc. Gross. Pay(hours. Wkd, rate. Of. Pay, gross. Pay) gross. Label. Text = gross. Pay. To. String("C 2") End Sub
Look into Memory of variables The variables used in exchange information between the calc. Button's click event procedure and the Calc. Gross. Pay procedures are allocated as follows: Variable Value Address In the calling procedure: hours. Wkd rate. Of. Pay 41. 0 8. 0 40000 40016 In the called procedure: hours. Wkd rate. Of. Pay 41. 0 8. 0 60000 60016 In both procedures: Gross. Pay 332. 0 40032
Passing Variables by Reference (Cont'd) Example Private Sub Calc. Gross. Pay(By. Val hours As Decimal, _ By. Val rate As Decimal, _ By. Ref gross As Decimal) ' calculates gross pay If hours <= 40 D Then gross = hours * rate Else gross = hours * rate + (hours - 40 D) * rate / 2 D End If End Sub
Additional By. Val or By. Ref Example • Tutorial 6 -4 demonstrates the difference between parameters passed By. Val & By. Ref – Passed By. Val – Calling procedure does not “see” changes made to the value of an argument – Passed By. Ref – Calling procedure “sees” changes made to the value of an argument
Function Procedures Similar to a Sub procedure, a function procedure is a block of code that performs a specific task. Different from a Sub procedure, a function procedure returns a value upon completion of the task. The concepts of passing by value and passing by reference apply to both Sub procedures and Function procedures.
Declaring a Function [Access. Specifier] Function. Name ([Parameter. List]) _ As Data. Type [Statements] End Function • New keyword Function • Also new is As Data. Type which states the data type of the value to be returned • Return value is specified in a Return expression
Function Call Example sng. Total = Sum(sng. Value 1, sng. Value 2) Function Sum(By. Val sng. Num 1 As Single, _ By. Val sng. Num 2 As Single) As Single Dim sng. Result As Single sng. Result = sng. Num 1 + sng. Num 2 Return sng. Result End Function • sng. Value 1 & sng. Value 2 must be data type Single – Data types must agree with parameter list • sng. Total must be Single, agrees with return value • Tutorial 6 -5 demonstrates function use
Returning Nonnumeric Values Function Full. Name(By. Val str. First As String, _ By. Val str. Last As String) As String Dim str. Name As String str. Name = str. Last & ", " & str. First Return str. Name End Function Is. Valid(int. Num As Integer) As Boolean Dim bln. Status As Boolean If int. Num >= 0 And int. Num <= 100 Then bln. Status = True Else bln. Status = False End If Return bln. Status End Function
Visual Basic 2010 addition • Nullable types were added to Visual Basic 2008. In Visual Basic 2010 you can use them as parameters. Here are two examples: • ' Assign Nothing as the default value for nullable optional parameter. • • Sub Calculate (By. Val x As Integer, By. Val y As Integer, Optional By. Val z As Integer? = Nothing). . . End Sub ' Assign an integer value to a nullable optional paramter of type Double. Sub Process(By. Val x As Integer, By. Val y As Integer, Optional By. Val z As Double? = 10). . . End Sub
Debugging Involving Procedures • Step Into - continue to debug by single-stepping through a procedure • Step Over - run procedure without single-stepping, continue single-step after the call • Step Out - end single-stepping in procedure, continue single-step after the call • Tutorial 6 -6 provides examples
- Slides: 31