Page 183 - DCAP210_INTRODUCTION__TO_MICROPROCESSORS
P. 183
Unit 13: Subroutines
declaration variables called parameters. However, subroutines do not automatically return a Notes
result code or an argument to the caller.
You declare subroutines using the Sub keyword and end them using the End Sub statement.
13.1 Subroutine
13.1.1 Definition
Subroutines are a powerful programming tool, and the syntax of many programming languages
includes support for writing and using them. Judicious use of subroutines (for example, through
the structured programming approach) will often substantially reduce the cost of developing
and maintaining a large program, while increasing its quality and reliability. Subroutines, often
collected into libraries, are an important mechanism for sharing and trading software. The
discipline of object-oriented programming is based on objects and methods (which are subroutines
attached to these objects or object classes).
The structure of a subroutine is where Subroutine Name is the name of the subroutine and
argument through arguments are optional arguments, often called parameters that you can pass
to the subroutine. If you choose not to pass any arguments to the subroutine, the parentheses are
optional, as you will see in a moment. The name of a subroutine should adequately describe
what the subroutine is for. You must name subroutines using the same rules as variables; letters
and numbers are fine as long as the first character is not a number, and you cannot use symbols.
If you enter an invalid name for a subroutine
The following are some valid subroutine names:
• WelcomeTheUser
• PrintInvoice
• Meters2Yards
The following are some unacceptable subroutine names:
• User.Welcome
• 2Printer
• Miles 1.609
If you want, a subroutine can require that the code statement that calls that subroutine provide
one or more arguments or variables that the subroutine can work with. Any time you need
preexisting data to perform the task within the subroutine, arguments are very helpful. For
example, the following subroutine accepts an argument to be used in the subroutine as a message
to be displayed to the user:
13.1.2 Calling a Subroutine
Now that you've learned how to create a subroutine, how do you call one? You can call a subroutine
throughout the rest of the application once you've declared and created it. You can call subroutines
by using the Call keyword or just entering the name of the subroutine on a line of code. For
example, to call a subroutine called ShowMessage, you could enter
If you use Call, you must enclose the arguments in parentheses. This is simply a
convention that code requires.
13.1.3 Exiting a Subroutine
The code within your subroutine will execute until one of two things happens. First, the subroutine
might get down to the last line, the End Sub line, which terminates the subroutine and passes the
LOVELY PROFESSIONAL UNIVERSITY 177