Introduction to Procedures and Functions
Introduction to Procedures and Functions
Introduction to Procedures
A procedure is a small program that is meant to solve a relatively small problem. In fact, sometimes it is called a sub-program. A program developer writes the procedure and a user (the user is either you or another programmer) would only see the result. There are two categories of procedures you will use in your programs: those that have already been created thus made available to you, and those you will create yourself.
You can create a procedure manually or, if you are using Microsoft Visual Studio, code can be generated for you. To manually create a procedure, start by typing the Sub keyword followed by a name (like everything else, a procedure must have a name). At the end of the procedure, you must type End Sub. Therefore, the primary formula of a procedure is:
Sub ProcedureName() End Sub
The name of a procedure should follow the rules of names in the Visual Basic language. In addition:
To let the studio start a procedure for you, first create a module. In the body of the module, right-click and click Insert Snippet... In the menu, double-click Code Patterns, If, For Each, Property, etc... Double-click Properties, Procedures, Events. Double-click Define a Sub:
This would produce:
Module Exercise
Sub MySub()
End Sub
End Module
The section between the Sub and the End Sub lines is referred to as the body of the procedure. Here is an example:
Sub Assign() End Sub
The body of the procedure is used to define what, and how, the assignment should be carried. For example, if you need to use a variable, you can declare it and specify the kind of variable you need. There is no restriction on the type of variables that can be declared in a procedure. Here is an example in which a string variable is declared in the body of a procedure:
Sub Assign()
Dim strFullName As String
End Sub
In the same way, you can declare as many variables as you need inside of a procedure. The actions you perform inside of a procedure depend on what you are trying to accomplish. For example, a procedure can simply be used to create a string. The above procedure can be changed as follows:
Sub Assign()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
End Sub
Practical Learning: Introducing Procedures
Public Module Geometry
Sub ProcessSquare()
Dim dblSide As Double
Dim dblPerimeter As Double
dblSide = InputBox("Enter Side: ")
dblPerimeter = dblSide * 4
Console.WriteLine("=-= Square Characteristics=-=" & vbCrLf &
"Side: " & dblSide & vbCrLf &
"Perimeter: " & dblPerimeter)
End Sub
Sub Main()
End Sub
End Module
|
Calling a Sub Procedure |
Once you have a procedure, whether you created it or it is part of the Visual Basic language, you can use it. Using a procedure is also referred to as calling it. Before calling a procedure, you should first locate the section of code in which you want to use it. To call a simple procedure, type its name followed by parentheses in the section where you want to use it. Here is an example:
Module Exercise
Sub Assign()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
Console.WriteLine(strFullName)
End Sub
Friend Sub Main()
Assign()
End Sub
End Module
Besides using the name of a procedure to call it, you can also precede it with the Call keyword. Here is an example:
Module Exercise
Sub Assign()
Dim strFullName As String
strFullName = "Paul Bertrand Yamaguchi"
Console.WriteLine(strFullName)
End Sub
Friend Sub Main()
Call Assign()
End Sub
End Module
|
|
Module Central
Sub ProcessSquare()
Dim dblSide As Double
Dim dblPerimeter As Double
dblSide = InputBox("Enter Side: ")
dblPerimeter = dblSide * 4
Console.WriteLine("=-= Square Characteristics=-=" & vbCrLf &
"Side: " & dblSide & vbCrLf &
"Perimeter: " & dblPerimeter)
End Sub
Sub Main()
ProcessSquare()
End Sub
End Module
|
Procedures and Access Modifiers |
Like a variable, a procedure can use access modifiers. A procedure can be made a private procedure, a friendly procedure, or a public procedure, using the Private, the Friend, or the Public keywords respectively:
|
|
Public Module Geometry
Private Sub ProcessSquare()
Dim dblSide As Double
Dim dblPerimeter As Double
dblSide = InputBox("Enter Side: ")
dblPerimeter = dblSide * 4
Console.WriteLine("=-= Square Characteristics =-=" & vbCrLf &
"Side: " & dblSide & vbCrLf &
"Perimeter: " & dblPerimeter)
End Sub
Public Sub Main()
ProcessSquare()
End Sub
End Module
Introduction to Functions
Introduction
Like a procedure, a function is a sub-program used to perform an assignment. The main difference between a procedure and a function is that, after carrying its assignment, a function gives back a result. We also say that a function "returns a value". To distinguish both, there is a different syntax you use for a function.
You can manually create a function or, if you are using Microsoft Visual Basic, ask it to create code for you.
To manually create a function, you use the Function keyword followed by a name and parentheses. Unlike a procedure, because a function returns a value, you must specify the type of value the function will produce. To give this information, on the right side of the closing parenthesis, you can type the As keyword, followed by a data type. To indicate where a function stops, type End Function. As seen for a procedure, a function can have an access modifier. The rules for access modifiers are the same as we described for a procedure.
If you are using Microsoft Visual Basic and you want the studio to generate code for you, right-click inslde a module and click Insert Snippet... In the menu, double-click Code Patterns, If, For Each, Property, etc... Double-click Properties, Procedures, Events. Double-click Define a Function.
The minimum formula used to create a function is:
AccessModifier(s) Function FunctionName() As DataType End Function
The Function keyword is required. The name of a function follows the same rules and suggestions we reviewed for sub procedures. The As keyword may be required (in the next sections, we will review the alternatives to the As DataType expression).
The DataType indicates the type of value the function will return. If the function will produce a word or a group of words, you can create it as String. The other data types are also valid in the contexts we reviewed them. Here is an example:
Function GetFullName() As String
End Function
As done with the variables, you can also use a type character as the return type of a function and omit the As DataType expression. The type character is typed on the right side of the function name and before the opening parenthesis. An example would be GetFullname$(). As with the variables, you must use the appropriate type character for the function:
| Character | The function must return |
| $ | a String type |
| % | a Byte, Short, Int16, or In32 |
| & | an Int64 or a Long |
| ! | a Single type |
| # | a Double |
| @ | a Long integer |
Here is an example:
Function GetFullName$()
End Function
As mentioned already, the section between the Function and the End Function lines is the body of the function. It is used to describe what the function does. As done on a sub procedure, one of the actions you can perform in a function is to declare a (local) variable and use it as you see fit. Here is an example:
Function CallMe() As String
Dim Salute As String
Salute = "You can call me Al"
End Function
|
Returning a Value From a Function |
After performing an assignment in a function, to indicate the value it returns, somewhere after the assignment and before the End Function line, you can type the name of the function, followed by the = sign, followed by the value the function returns. Here is an example in which a function returns a name:
Function GetFullName$()
Dim FirstName As String, LastName As String
FirstName = InputBox("Enter First Name: ")
LastName = InputBox("Enter Last Name: ")
GetFullName = LastName & ", " & FirstName
End Function
Alternatively, instead of using the name of the function to indicate the value it returns, you can type Return, followed by the value or the expression that the function returns. Based on this, the above function could also be created as follows:
Function GetFullName$()
Dim FirstName As String, LastName As String
FirstName = InputBox("Enter First Name: ")
LastName = InputBox("Enter Last Name: ")
Return LastName & ", " & FirstName
End Function
You can also use some local variables in the function to perform an assignment and then assign their result to the name of the function.
|
|
New Convention:From now on, in our lessons, to refer to a procedure or function, we will use the name of a procedure followed by parentheses. For example, we may write "the Convert() procedure" or "the Convert() function". |
|
|
Module Geometry
Private Sub ProcessSquare()
Dim dblSide As Double
Dim dblPerimeter As Double
dblSide = InputBox("Enter Side: ")
dblPerimeter = dblSide * 4
Console.WriteLine("=-= Square Characteristics=-=" & vbCrLf &
"Side: " & dblSide & vbCrLf &
"Perimeter: " & dblPerimeter)
End Sub
Private Function CalculatePerimeter() As Double
Dim dblLength As Double
Dim dblWidth As Double
dblLength = InputBox("Enter Rectangle Length: ")
dblWidth = InputBox("Enter Rectangle Width: ")
CalculatePerimeter = (dblLength + dblWidth) * 2
End Function
Public Sub Main()
End Sub
End Module
|
Calling a Function |
As done for the sub procedure, in order to use a function in your program, you must call it. Like a sub procedure, to call a function, you can simply type its name in the desired section of the program. Here is an example:
Sub Main()
CallMe
End Sub
Since the primary purpose of a function is to return a value, to better take advantage of such a value, you can assign the name of a function to a variable in the section where you are calling the function. Here is an example:
Module Exercise
Function GetFullName$()
Dim FirstName As String, LastName As String
FirstName = InputBox("Enter First Name: ")
LastName = InputBox("Enter Last Name: ")
Return LastName & ", " & FirstName
End Function
Friend Sub Main()
Dim FullName$
FullName = GetFullName()
Console.WriteLine(FullName)
End Sub
End Module
Here is an example of running this program:



|
|
Public Module Rectangle
Private Function CalculatePerimeter() As Double
Dim dblLength As Double
Dim dblWidth As Double
dblLength = InputBox("Enter Rectangle Length: ")
dblWidth = InputBox("Enter Rectangle Width: ")
CalculatePerimeter = (dblLength + dblWidth) * 2
End Function
Public Sub Main()
Dim Perimeter As Double
Perimeter = CalculatePerimeter()
Console.WriteLine("=-= Square Characteristics=-=" & vbCrLf &
"Perimeter: " & Perimeter)
End Sub
End Module
|
The Main() Procedure |
The Visual Basic Language uses a special procedure and function called Main. Main is the entry point of a program as we have used it so far. Particularly, Main can be used as a procedure or a function. So far, we have used Main only as a procedure. To use Main as a function, type the Function keyword required for each function, followed by Main(), followed by As Integer. When declared like this, the Main function must return an integer. The most regularly return value is 0, which indicates that the function ended successfully. Here is an example:
Module Exercise
Friend Function GetFullName$()
Dim FirstName As String, LastName As String
FirstName = InputBox("Enter First Name: ")
LastName = InputBox("Enter Last Name: ")
Return LastName & ", " & FirstName
End Function
Friend Function Main() As Integer
Dim FullName$
FullName = GetFullName()
Console.WriteLine(FullName)
Return 0
End Function
End Module
|
|
Module Geometry
Private Sub ProcessSquare()
Dim dblSide As Double
Dim dblPerimeter As Double
dblSide = InputBox("Enter Side: ")
dblPerimeter = dblSide * 4
Console.WriteLine("=-= Square Characteristics=-=" & vbCrLf &
"Side: " & dblSide & vbCrLf &
"Perimeter: " & dblPerimeter)
End Sub
Private Function CalculatePerimeter() As Double
Dim dblLength As Double
Dim dblWidth As Double
dblLength = InputBox("Enter Rectangle Length: ")
dblWidth = InputBox("Enter Rectangle Width: ")
CalculatePerimeter = (dblLength + dblWidth) * 2
End Function
Public Function Main() As Integer
Dim Perimeter As Double
Perimeter = CalculatePerimeter()
Console.WriteLine("=-= Square Characteristics=-=" & vbCrLf &
"Perimeter: " & Perimeter)
Return 0
End Function
End Module
|
Maintenance of Procedures |
|
Introduction |
Depending on an author, in the Visual Basic language, the word "procedure" includes either a procedure created with the Sub keyword, or a function created with the Function keyword. In the same way, for the rest of our lessons, the word procedure will be used to represent both types. Only when we want to be precise will we use the expression "a procedure" or "a sub-procedure" to explicitly mean the type of procedure that does not return a value. When the word "function" is used in our lessons, it explicitly refers to the type of procedure that returns a value.
|
Accessing a Procedure |
If you are using a text editor to write your code, you can use the Edit main menu to do a search on the name of the procedure. If you are using Microsoft Visual Basic, in the top section of the Class View, click the name of the module in which the procedure exists. In the bottom section of the Class View, double-click the name of the procedure. The Code Editor would jump to where the procedure was defined. As an alternative, if you see a section where the procedure gets called in the Code Editor, right-click its name and click Go To Definition. This would select the name of the procedure where it is defined.
|
Renaming a Procedure |
You can rename a procedure the same you would proceed for a variable. If you are using a text editor like Notepad, you can do a search on its name and replace all instances with a new name. If you are using Microsoft Visual Basic, Find the name of the procedure where it is defined and change it:

Then click the button under the new name, click the arrow on the button and click Rename.
The Scope and Lifetime of a Variable
Local Variables
The scope of a variable determines the areas of code where the variable is available. You may have noticed that, so far, we declared all our variables only inside of Main(). Actually, the Visual Basic language allows you to declare variables outside of Main() (and outside of a particular procedure).
A variable declared inside of a procedure such as Main() is referred to as a local variable. Such as variable cannot be accessed by another part (such as another procedure) of the program.
Global Variables
A variable that is declared outside of any procedure is referred to as global. To declare a global variable, use the same formula as we have done so far. For example, just above the Sub Main() line, you can type Dim, followed by the name of the variable, the As keyword, its type and an optional initialization. Here is an example:
Module Exercise
Dim DateOfBirth As Date
Sub Main()
End Sub
End Module
As mentioned above, you can initialize the global variable when or after declaring it. Here are two examples:
Module Exercise
Dim UnitPrice As Double
Dim DateOfBirth As Date = #12/5/1974#
Sub Main()
UnitPrice = 24.95
Console.WriteLine("Date of Birth: " & DateOfBirth)
Console.WriteLine("Unit Price: " & UnitPrice)
End Sub
End Module
As we will see when studying procedures, a global variable can be accessed by any other procedure (or even class) of the same file. In most cases, a global variable must be declared inside of a module, that is, between the Module ModName and the End Module lines but outside of a procedure. Based on this, such a variable is said to have module scope because it is available to anything inside of that module.
Practical Learning: Declaring Global Constants
Module CleaningOrder
Dim UnitPriceShirts As Double = 1.25
Dim UnitPricePants As Double = 1.95
Dim UnitPriceOtherItems As Double = 3.25
Dim TaxRate As Double = 5.75
Sub Main()
Dim CustomerName As String, CustomerPhone As String
. . . No Change
End Sub
End Module| Customer Name: | Shawn Nitty |
| Customer Phone: | (301) 423-7744 |
| Order Date: | 04/11/2008 |
| Order Time | 09:12 |
| Number of Shirts: | 0 |
| Number of Pants: | 2 |
| Number of Other Items: | 0 |
Accessing a Variable
As mentioned already, you will write your code in normal text editors, whether using Notepad, the Code Editor of Microsoft Visual Studio, or else. Also, you may be familiar already with how to look for a character, a symbol, a word, or a group of words in a document. Just as reminder, on the main menu of the application, you can click Edit -> Find... This would display a dialog box where you can type the item and click Find. If you are using Microsoft Visual Studio and if you want to find different occurrences of a known character, symbol, word, or group of words, first select that item. Then:
In the same way, if you have a variable that is used more than once in your code and you want to see all places where that variable is used, simply click the name (and wait two seconds) and all of its occurrences would be highlighted:

To get a list of all sections where the variable is used, if you are using Microsoft Visual Studio:

This would produce a list of all sections where the variable is used and would display the list in the Find Symbol Results window:

To access a particular section where the variable is used, double-click its entry in the list int the Find Symbol Results window.
Normally, from your knowledge of using computers, you probably already know how to select, cut, and copy text. These two operations can be valuable to save code in Microsoft Visual Studio. This means that, if you have code you want to use in different sections, you can preserve it somewhere to access it whenever necessary.
To save code to use over and over again, first type the code in any text editor, whether in Notepad, Microsoft Word, or the Code Editor of Microsoft Visual Studio. You can use code from any document where text can be copied, including a web page. Select that code and copy it to the clipboard. To preserve it, in Microsoft Visual Studio, display the Toolbox (on the main menu, you can click View -> Toolbox). Right-click an empty area on the Toolbox and click Paste:

An alternative is to select the code, whether in the Code Editor or in a text editor. Then drag it and drop it on the Toolbox. In the same way, you can add different code items to the Toolbox. After pasting or adding the code to the Toolbox, it becomes available. To use that code, drag it from the Toolbox and drop it in the section of the Code Editor where you want to use it.
|
Renaming a Variable |
As we will see throughout our lessons, there are many names you will use in your programs. After creating a name, in some cases you will have to change it. You can find where the name is and edit it. If the name is used in many places, you can continue looking for it and modify it. There is a chance you will make a mistake. If you are writing your code using a text editor, you can use the Edit -> Replace option of the main menu to find and replace every instance of that name. You can use the same approach in the Code Editor. Unfortunately, this technique works for only one file. If your project has many files and the name is used in those files, it would be cumbersome to remember to change the name in all of them.
Microsoft Visual Studio makes it easy to find and change a name wherever it is used. Consider the following code:
Module Exercise
Public Sub Main()
Dim nbr As Integer
nbr = 148
Console.WriteLine(nbr)
End Sub
End Module
To change the name of a variable, in the Code Editor, double-click the name of the variable and edit (change) it. The name will then have a small underline:

If you position your mouse on it, a tag would appear and you can click the arrow to reveal a short menu:

If you click the Rename option, all instances of the variable would be changed.
Accessing a Variable's Declaration
If you create a long document that has many lines of code, in a certain section you may encounter a variable but you want to find out where it was declared. If you are using Microsoft Visual Studio, to access the place where a variable was declared:

In both cases, the caret would jump to where the variable was declared.
Accessing a Line of Code by its Index
If you are using the Code Editor of Microsoft Visual Studio, if you create a long document that has many lines of code, if you want to jump to a certain line of code:
This would display a dialog box. Enter the line number and click OK or press Enter.
Practical Learning: Ending the Lesson
|
|
|||
| Previous | Copyright © 2008-2026, FunctionX | Monday 14 February 2016 | Next |
|
|
|||