80 likes | 97 Views
Learn about the benefits of using subprograms and procedures in programming, including improved code reusability, better organization, and avoiding side effects. Explore the differences between global and local variables and understand the importance of careful variable declaration.
E N D
Subprograms • A subprogram is a part of the program that has all the elements of the program itself. • Subprograms facilitate the translation of the top-down algorithm to the final program because they allow us to concentrate on one task at a time. • Subprograms are “called” or “activated” from the “Main Program”
Subprograms: Procedures • For now we will look at a type of subprogram called a procedure. • A Pascal procedure is similar in construction to a program. It can contain its own VAR declaration and/or CONST definition, and it contains its own statement part which begins with BEGIN and ends with END
Procedures (con’t) • Differences between the construction of a program and a procedure: • The reserved word PROCEDURE replaces the reserved word PROGRAM. • The final END is followed by a semicolon instead of a period.
Advantages of using procedures • If you want to perform a task more than once in a program, you just reference the procedure each time. This avoids repeating the same code. • The main program can be written as a sequence of tasks which makes it easier for humans to understand.
Global vs. Local variables • Global identifiers are declared in the main program. These variables can be used in the main program as well as in the procedures that are called from the main program. • Local identifiers are declared in the procedures. These variables can only be used by the procedure in which they are declared.
It is not a good idea to use global variables in your procedures Doing so can cause side effects. A side effect occurs when you unintentionally assign a new value to a global variable within a procedure. When you return to the main program and use that variable, you will get an unexpected result.
What if we declare the same identifier in both the main program and one of its procedures? • The compiler will establish two different memory locations for the variables. It is as if they had different identifiers. • One location is available in the main program. • The other is available only in the procedure. ie. It takes precedence inside the procedure.
Homework #5 • Due November 2, 1999 • It is homework #4 on Marateck’s homepage:http://cs.nyu.edu/courses/fall97/A22.0002/hw4.html