5.1 Variables, Binding and Scope
5.1 Variables, Binding and Scope
5.1 Variables, Binding and Scope
• Variables
– Names and Attributes
• Initialization
• Constants
• Binding
• Type Checking
– Strong Typing
– Type Compatibility
• Scope
– Scope and Lifetime
– Referencing Environments
• Sebesta Chapter 5
Variables: Introduction
3
• User-defined names
• Design issues for names:
– Maximum length?
– Are connector characters allowed?
– Are names case sensitive?
– Are some words reserved words or keywords?
– ONLY UPPERCASE LETTERS ALLOWED?
Name Length
6
• Pascal _
– underscore only
• Modula-2, and FORTRAN 77
– none allowed
• Java
– $,_ (but $ is by the system used for inner classes)
• Common Lisp
– many, including *,+,-,_, …
• Advantages of having connectors?
• Disadvantages of having connectors?
Case Sensitivity in Variable Names 8
• keyword
– special only in certain contexts
• Disadvantage: poor readability
• reserved word
– special word that can’t be re-used by programmer
• Aids readability
– Used to delimit or separate statement clauses
Named Constants
10
• Named constant
– variable bound to a value only when it is bound to
storage
• Advantages:
– readability and modifiability
• Used to parameterize programs
• The binding of values constants can be either
static (called manifest constants) or dynamic
– Pascal: literals only
– FORTRAN 90: constant-valued expressions
– Ada, C++, and Java: expressions of any kind
Variable Addresses
11
• Created by
– pointers
– reference variables
– C and C++ unions
– Pascal variant-records
– and by parameters!
• Binding = association
– for a variable, the association of l-value to r-value
• Binding time
– time (during execution) when l-value is associated
with r-value
Variable Initialization
15
• Initialization
– the initial binding of a variable to a value
• Static
– first occurs before run time and
– remains unchanged throughout program execution
• Dynamic
– first occurs during execution, or
– can change during execution of the program.
Type Bindings
18
• Lifetime
– the time during which it is bound to a particular memory cell
• Allocation
– getting a cell from a pool of available cells
• De-allocation
– returning a cell back into the pool
Static Variables
22
• Static variables
– bound to memory cells before
program execution begins
– remain bound to same memory cells
until program execution terminates
• Example
– (defconstant foo)
– all FORTRAN 77 variables
– C static variables
• Advantages:
– efficiency (direct addressing)
– history-sensitive subprogram support
• Disadvantage:
– less flexible (no recursion)
Stack Dynamic Variables
23
• Stack-dynamic
– allocation during
execution at declaration
elaboration time
Heap Variables (Dynamic) 25
• Implicit
– Automatic
• Explicit
– programmer’s
instruction
Explicit Heap-Dynamic Variables 26