Chapter 6 Procedures and Functions - University of Houston

download report

Transcript Chapter 6 Procedures and Functions - University of Houston

Chapter 6 Procedures and Functions
Instructor: Bindra Shrestha
University of Houston – Clear Lake
CSCI 3131.01
Dr. Xinhua Chen
Starting Out with Visual Basic 2010
by Tony Gaddis and Kip Irvine
Passing arguments to Procedures
• Step into, over, and out of procedures and
• 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 IsNumeric
• A method can be either a procedure or a function
A moderately complex program needs to perform multiple tasks.
A procedure is a block of program code that performs a specific
A program can be considered as the assembly of multiple
Execution of a procedure is commonly referred to as calling a
Most Visual Basic procedures are Sub procedures and Function
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
An analogy of procedure calls:
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 btnGo_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnGo.Click
' This procedure calls the DisplayMessage procedure.
lstOutput.Items.Add("Hello from btnGo_Click procedure.")
lstOutput.Items.Add("Now I am calling the " & _
"DisplayMessage procedure."
lstOutput.Items.Add("Now I am back " _
& "in the btnGo_Click procedure.")
End Sub
Returns to
Sub DisplayMessage()
'A Sub procedure that displays a message.
lstOutput.Items.Add("Hello from DisplayMessage procedure.")
End Sub
Declaring a Procedure
[AccessSpecifier] Sub ProcedureName ([ParameterList])
End Sub
• AccessSpecifier is optional and establishes
accessibility to the program
• Sub and End are keywords
• ProcedureName used to refer to procedure
– Use Pascal casing, capitalize 1st character of the name and
each new word in the name
• ParameterList 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 DisplayGrade()
' Display the intAverage score.
lblAverage.Text = intAverage.ToString()
' Determine and display the letter grade.
Select Case intAverage
Case 90 To 100
lblLetterGrade.Text = "A"
Case 80 To 90
lblLetterGrade.Text = "B"
Case 70 To 79
lblLetterGrade.Text = "C"
Case 60 To 69
lblLetterGrade.Text = "D"
Case Else
lblLetterGrade.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 VariableName As DataType
– Scope is still only within the procedure
– But variable exists for lifetime of application
• Argument – a value passed to a procedure
• We’ve already done this with functions
– Value = CInt(txtInput.Text)
– Calls the CInt function and passes txtInput.Text as
an argument
• A procedure must be declared with a parameter
list in order to accept an argument
Passing Multiple Arguments
ShowSum(intValue1, intValue2)
' calls ShowSum procedure
Sub ShowSum(ByVal intNum1 As Integer, _
ByVal intNum2 As Integer)
' This procedure accepts two arguments, and prints
' their sum on the form.
Dim intSum As Integer
intSum = intNum1 + intNum2
MessageBox.Show("The sum is " & intSum.ToString)
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 ByVal in the variable declaration.
When the procedure is invoked, only the value of the variable is
passed to the procedure.
Private Sub DisplayMessage(ByVal pet As String, ByVal years
As String)
messageLabel.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 getInfoButton_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles getInfoButton.Click
Dim petName As String
Dim petAge As String
petName = InputBox("Pet's name:", "Name Entry")
petAge = InputBox("Pet's age (years):", "Age Entry")
DisplayMessage(petName, petAge)
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 ByRef keyword in the parameter list.
Passing Variables by Reference (Cont'd)
Private Sub calcButton_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles calcButton.Click
Dim hoursWkd As Decimal
Dim rateOfPay As Decimal
Dim grossPay As Decimal
hoursWkd = Convert.ToDecimal(hoursListBox.SelectedItem)
rateOfPay = Convert.ToDecimal(rateListBox.SelectedItem)
CalcGrossPay(hoursWkd, rateOfPay, grossPay)
grossLabel.Text = grossPay.ToString("C2")
End Sub
Look into Memory of variables
The variables used in exchange information between the
calcButton's click event procedure and the CalcGrossPay
procedures are allocated as follows:
In the calling procedure: hoursWkd
In the called procedure:
In both procedures:
Passing Variables by Reference (Cont'd)
Private Sub CalcGrossPay(ByVal hours As Decimal, _
ByVal rate As Decimal, _
ByRef gross As Decimal)
' calculates gross pay
If hours <= 40D Then
gross = hours * rate
gross = hours * rate + (hours - 40D) * rate / 2D
End If
End Sub
Additional ByVal or ByRef Example
• Tutorial 6-4 demonstrates the difference between
parameters passed ByVal & ByRef
– Passed ByVal
– Calling procedure does not
“see” changes made to the
value of an argument
– Passed ByRef
– 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
Declaring a Function
[AccessSpecifier] Function FunctionName ([ParameterList]) _
As DataType
End Function
• New keyword Function
• Also new is As DataType which states the data type of
the value to be returned
• Return value is specified in a Return expression
Function Call Example
sngTotal = Sum(sngValue1, sngValue2)
Function Sum(ByVal sngNum1 As Single, _
ByVal sngNum2 As Single) As Single
Dim sngResult As Single
sngResult = sngNum1 + sngNum2
Return sngResult
End Function
• sngValue1 & sngValue2 must be data type Single
– Data types must agree with parameter list
• sngTotal must be Single, agrees with return value
• Tutorial 6-5 demonstrates function use
Returning Nonnumeric Values
Function FullName(ByVal strFirst As String, _
ByVal strLast As String) As String
Dim strName As String
strName = strLast & ", " & strFirst
Return strName
End Function
Function IsValid(intNum As Integer) As Boolean
Dim blnStatus As Boolean
If intNum >= 0 And intNum <= 100 Then
blnStatus = True
blnStatus = False
End If
Return blnStatus
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 (ByVal x As Integer, ByVal y As Integer, Optional ByVal z As Integer? = Nothing)
End Sub
' Assign an integer value to a nullable optional paramter of type Double.
Sub Process(ByVal x As Integer, ByVal y As Integer, Optional ByVal 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