If you already have knowledge about variables and declarations in Pascal, you can proceed to learn about the variable scope in Pascal. The scope in any program is the region where variables are defined. If a variable exceeds its scope, it cannot be accessed. For a deeper understanding of variable scope in Pascal, continue reading the content below by Mytour.
Scope of Variables in Pascal
Scope of variables declared in the Pascal programming language includes:
- Inside a subroutine or block (known as local variables).
- Outside all subroutines, known as global variables.
- In the definition of subroutine parameters, known as formal parameters.
For a deeper understanding, details about local variables, global variables, and subroutine parameters can be found in the following article by Mytour.
Local Variables in Pascal
Variables declared within a subroutine or a block are called local variables. These variables are only used within the statements inside the subroutine or code block.
Below is an example of local variables in Pascal. In this example, all variables a, b, and c are local variables in the program named exLocal.
When the above code is compiled and executed, it will return the following result:
value of a = 10 b = 20 c = 30
To enhance the program, you create a Pascal procedure named display, which will have variables a, b, and c and display their values directly on the exLocal program.
When the above code is compiled and executed, it will return the following result:
Global Variables in Pascal
Global variables in Pascal are defined outside of a function, typically at the beginning of programs. These variables will hold values throughout your program and can be accessed within any functions defined for the program.
Global variables can be accessed by any functions. This means a global variable can be used throughout the program after declaration. Below is an example of using global and local variables:
When the above code is compiled and executed, it will return the following result:
Note: The display procedure has access to variables a, b, and c, which are global variables related to the display procedure as well as its own local variables. A program can have variables with the same name as local and global variables but the value of a local variable inside a function will be prioritized.
For example:
In the following example, local variables for the display procedure, named a, b, c, share the same identifiers:
When the above code snippet is compiled and executed, it will yield the following outcome:
Hope this article by Mytour provides you with useful insights into variable scope in Pascal. Subsequent articles by Mytour will further introduce strings in Pascal. Stay tuned for the latest articles on Mytour, where you can also explore Pascal operators.
