PPL Unit 2 Total Notes
PPL Unit 2 Total Notes
• Introduction
• Names
• Variables
• The Concept of Binding
• Scope
• Scope and Lifetime
• Referencing Environments
• Named Constants
PPL - Unit 2
Introduction
PPL - Unit 2
Names
PPL - Unit 2
Names (continued)
• Length
– If too short, they cannot be connotative
– Language examples:
• FORTRAN 95: maximum of 31
• C99: no limit but only the first 63 are significant;
also, external names are limited to a maximum of
31
• C#, Ada, and Java: no limit, and all are significant
• C++: no limit, but implementers often impose one
PPL - Unit 2
Names (continued)
• Special characters
– PHP: all variable names must begin with dollar
signs
– Perl: all variable names begin with special
characters, which specify the variable’s type
– Ruby: variable names that begin with @ are
instance variables; those that begin with @@ are
class variables
PPL - Unit 2
Names (continued)
• Case sensitivity
– Disadvantage: readability (names that look alike
are different)
• Names in the C-based languages are case sensitive
• Names in others are not
• Worse in C++, Java, and C# because predefined
names are mixed case (e.g.
IndexOutOfBoundsException)
PPL - Unit 2
Names (continued)
• Special words
– An aid to readability; used to delimit or separate
statement clauses
• A keyword is a word that is special only in certain
contexts, e.g., in Fortran
– Real VarName (Real is a data type followed with a name,
therefore Real is a keyword)
– Real = 3.4 (Real is a variable)
– A reserved word is a special word that cannot
be used as a user-defined name
– Potential problem with reserved words: If there
are too many, many collisions occur (e.g.,
COBOL has 300 reserved words!)
PPL - Unit 2
Variables
PPL - Unit 2
Variables Attributes
PPL - Unit 2
Variables Attributes (continued)
PPL - Unit 2
The Concept of Binding
PPL - Unit 2
Possible Binding Times
PPL - Unit 2
Type Binding
PPL - Unit 2
Explicit/Implicit Declaration
• An explicit declaration is a program
statement used for declaring the types of
variables
• An implicit declaration is a default
mechanism for specifying types of variables
(the first appearance of the variable in the
program)
• FORTRAN, BASIC, and Perl provide implicit
declarations (Fortran has both explicit and
implicit)
– Advantage: writability
– Disadvantage: reliability (less trouble with Perl)
PPL - Unit 2
Dynamic Type Binding
PPL - Unit 2
Variable Attributes (continued)
PPL - Unit 2
Categories of Variables by Lifetimes
PPL - Unit 2
Categories of Variables by Lifetimes
• Stack-dynamic--Storage bindings are created for
variables when their declaration statements are
elaborated.
(A declaration is elaborated when the executable
code associated with it is executed)
• If scalar, all attributes except address are statically
bound
– local variables in C subprograms and Java methods
• Advantage: allows recursion; conserves storage
• Disadvantages:
– Overhead of allocation and deallocation
– Subprograms cannot be history sensitive
– Inefficient references (indirect addressing)
PPL - Unit 2
Categories of Variables by Lifetimes
• Explicit heap-dynamic -- Allocated and
deallocated by explicit directives, specified by the
programmer, which take effect during execution
• Referenced only through pointers or references,
e.g. dynamic objects in C++ (via new and delete),
all objects in Java
• Advantage: provides for dynamic storage
management
• Disadvantage: inefficient and unreliable
PPL - Unit 2
Categories of Variables by Lifetimes
PPL - Unit 2
Variable Attributes: Scope
PPL - Unit 2
Static Scope
PPL - Unit 2
Scope (continued)
PPL - Unit 2
Blocks
PPL - Unit 2
Declaration Order
PPL - Unit 2
Declaration Order (continued)
PPL - Unit 2
Global Scope
PPL - Unit 2
Global Scope (continued)
• PHP
– Programs are embedded in XHTML markup
documents, in any number of fragments, some
statements and some function definitions
– The scope of a variable (implicitly) declared in a
function is local to the function
– The scope of a variable implicitly declared
outside functions is from the declaration to the
end of the program, but skips over any
intervening functions
• Global variables can be accessed in a function
through the $GLOBALS array or by declaring it global
PPL - Unit 2
Global Scope (continued)
• Python
– A global variable can be referenced in functions,
but can be assigned in a function only if it has
been declared to be global in the function
PPL - Unit 2
Evaluation of Static Scoping
PPL - Unit 2
Dynamic Scope
PPL - Unit 2
Scope Example
Big
-declaration of X
Sub1
-declaration of X -
...
call Sub2
... Big calls Sub1
Sub1 calls Sub2
Sub2 Sub2 uses X
...
-reference to X -
...
...
call Sub1
…
PPL - Unit 2
Scope Example
• Static scoping
– Reference to X is to Big's X
• Dynamic scoping
– Reference to X is to Sub1's X
• Evaluation of Dynamic Scoping:
– Advantage: convenience
– Disadvantages:
1. While a subprogram is executing, its variables are
visible to all subprograms it calls
2. Impossible to statically type check
3. Poor readability- it is not possible to statically
determine the type of a variable
PPL - Unit 2
Scope and Lifetime
PPL - Unit 2
Referencing Environments
PPL - Unit 2
Named Constants
PPL - Unit 2
Summary
PPL - Unit 2
Data Types
• Introduction
• Primitive Data Types
• Character String Types
• User-Defined Ordinal Types
• Array Types
• Associative Arrays
• Record Types
• Union Types
• Pointer and Reference Types
PPL - Unit 2
Introduction
PPL - Unit 2
Primitive Data Types
PPL - Unit 2
Primitive Data Types: Integer
PPL - Unit 2
Primitive Data Types: Floating Point
PPL - Unit 2
Primitive Data Types: Complex
PPL - Unit 2
Primitive Data Types: Decimal
PPL - Unit 2
Primitive Data Types: Boolean
• Simplest of all
• Range of values: two elements, one for
“true” and one for “false”
• Could be implemented as bits, but often as
bytes
– Advantage: readability
PPL - Unit 2
Primitive Data Types: Character
PPL - Unit 2
Character String Types
PPL - Unit 2
Character String Types Operations
• Typical operations:
– Assignment and copying
– Comparison (=, >, etc.)
– Catenation
– Substring reference
– Pattern matching
PPL - Unit 2
Character String Type in Certain
Languages
• C and C++
– Not primitive
– Use char arrays and a library of functions that provide
operations
• SNOBOL4 (a string manipulation language)
– Primitive
– Many operations, including elaborate pattern matching
• Fortran and Python
– Primitive type with assignment and several operations
• Java
– Primitive via the String class
• Perl, JavaScript, Ruby, and PHP
- Provide built-in pattern matching, using regular
expressions
PPL - Unit 2
Character String Length Options
PPL - Unit 2
Character String Type Evaluation
• Aid to writability
• As a primitive type with static length, they
are inexpensive to provide--why not have
them?
• Dynamic length is nice, but is it worth the
expense?
PPL - Unit 2
Character String Implementation
PPL - Unit 2
Compile- and Run-Time Descriptors
Compile-time Run-time
descriptor for descriptor for
static strings limited dynamic
strings
PPL - Unit 2
User-Defined Ordinal Types
PPL - Unit 2
Enumeration Types
PPL - Unit 2
Evaluation of Enumerated Type
PPL - Unit 2
Subrange Types
Day1: Days;
Day2: Weekday;
Day2 := Day1;
PPL - Unit 2
Subrange Evaluation
• Aid to readability
– Make it clear to the readers that variables of
subrange can store only certain range of values
• Reliability
– Assigning a value to a subrange variable that is
outside the specified range is detected as an
error
PPL - Unit 2
Implementation of User-Defined
Ordinal Types
PPL - Unit 2
Array Types
PPL - Unit 2
Array Design Issues
PPL - Unit 2
Array Indexing
PPL - Unit 2
Arrays Index (Subscript) Types
PPL - Unit 2
Subscript Binding and Array Categories
PPL - Unit 2
Subscript Binding and Array Categories
(continued)
PPL - Unit 2
Subscript Binding and Array Categories
(continued)
PPL - Unit 2
Subscript Binding and Array Categories
(continued)
• C and C++ arrays that include static
modifier are static
• C and C++ arrays without static modifier
are fixed stack-dynamic
• C and C++ provide fixed heap-dynamic
arrays
• C# includes a second array class ArrayList
that provides fixed heap-dynamic
• Perl, JavaScript, Python, and Ruby support
heap-dynamic arrays
PPL - Unit 2
Array Initialization
PPL - Unit 2
Heterogeneous Arrays
PPL - Unit 2
Array Initialization
• C-based languages
– int list [] = {1, 3, 5, 7}
– char *names [] = {“Mike”, “Fred”,“Mary Lou”};
• Ada
– List : array (1..5) of Integer :=
(1 => 17, 3 => 34, others => 0);
• Python
– List comprehensions
list = [x ** 2 for x in range(12) if x % 3 == 0]
puts [0, 9, 36, 81] in list
PPL - Unit 2
Arrays Operations
• APL provides the most powerful array processing
operations for vectors and matrixes as well as
unary operators (for example, to reverse column
elements)
• Ada allows array assignment but also catenation
• Python’s array assignments, but they are only
reference changes. Python also supports array
catenation and element membership operations
• Ruby also provides array catenation
• Fortran provides elemental operations because
they are between pairs of array elements
– For example, + operator between two arrays results in an
array of the sums of the element pairs of the two arrays
PPL - Unit 2
Rectangular and Jagged Arrays
PPL - Unit 2
Slice Examples
• Fortran 95
Integer, Dimension (10) :: Vector
Integer, Dimension (3, 3) :: Mat
Integer, Dimension (3, 3) :: Cube
PPL - Unit 2
Slices Examples in Fortran 95
PPL - Unit 2
Implementation of Arrays
PPL - Unit 2
Accessing Multi-dimensioned Arrays
PPL - Unit 2
Locating an Element in a Multi-
dimensioned Array
•General format
Location (a[I,j]) = address of a [row_lb,col_lb] +
(((I - row_lb) * n) + (j - col_lb)) * element_size
PPL - Unit 2
Compile-Time Descriptors
PPL - Unit 2
Associative Arrays
PPL - Unit 2
Record Types
PPL - Unit 2
Definition of Records in COBOL
PPL - Unit 2
Definition of Records in Ada
PPL - Unit 2
References to Records
• Record field references
1. COBOL
field_name OF record_name_1 OF ... OF record_name_n
2. Others (dot notation)
record_name_1.record_name_2. ... record_name_n.field_name
PPL - Unit 2
Operations on Records
PPL - Unit 2
Evaluation and Comparison to Arrays
PPL - Unit 2
Implementation of Record Type
PPL - Unit 2
Unions Types
PPL - Unit 2
Discriminated vs. Free Unions
PPL - Unit 2
Ada Union Types
PPL - Unit 2
Ada Union Type Illustrated
PPL - Unit 2
Evaluation of Unions
PPL - Unit 2
Pointer and Reference Types
PPL - Unit 2
Design Issues of Pointers
PPL - Unit 2
Pointer Operations
PPL - Unit 2
Pointer Assignment Illustrated
PPL - Unit 2
Problems with Pointers
PPL - Unit 2
Pointers in Ada
PPL - Unit 2
Pointers in C and C++
PPL - Unit 2
Pointer Arithmetic in C and C++
float stuff[100];
float *p;
p = stuff;
PPL - Unit 2
Reference Types
PPL - Unit 2
Evaluation of Pointers
PPL - Unit 2
Representations of Pointers
PPL - Unit 2
Dangling Pointer Problem
PPL - Unit 2
Heap Management
PPL - Unit 2
Reference Counter
PPL - Unit 2
Mark-Sweep
PPL - Unit 2
Variable-Size Cells
PPL - Unit 2
Type Checking
PPL - Unit 2
Type Checking (continued)
PPL - Unit 2
Strong Typing
Language examples:
– FORTRAN 95 is not: parameters, EQUIVALENCE
– C and C++ are not: parameter type checking
can be avoided; unions are not type checked
– Ada is, almost (UNCHECKED CONVERSION is
loophole)
(Java and C# are similar to Ada)
PPL - Unit 2
Strong Typing (continued)
PPL - Unit 2
Name Type Equivalence
PPL - Unit 2
Structure Type Equivalence
PPL - Unit 2
Type Equivalence (continued)
PPL - Unit 2
Theory and Data Types (continued)
PPL - Unit 2
Summary
PPL - Unit 2
Expressions and
Assignment Statements
• Introduction
• Arithmetic Expressions
• Overloaded Operators
• Type Conversions
• Relational and Boolean Expressions
• Short-Circuit Evaluation
• Assignment Statements
• Mixed-Mode Assignment
PPL - Unit 2
Introduction
PPL - Unit 2
Arithmetic Expressions
PPL - Unit 2
Arithmetic Expressions: Design Issues
PPL - Unit 2
Arithmetic Expressions: Operators
PPL - Unit 2
Arithmetic Expressions: Operator
Precedence Rules
PPL - Unit 2
Arithmetic Expressions: Operator
Associativity Rule
• The operator associativity rules for expression evaluation
define the order in which adjacent operators with the same
precedence level are evaluated
PPL - Unit 2
Ruby Expressions
PPL - Unit 2
Arithmetic Expressions: Conditional
Expressions
• Conditional Expressions
– C-based languages (e.g., C, C++)
– An example:
average = (count == 0)? 0 : sum / count
PPL - Unit 2
Arithmetic Expressions: Operand
Evaluation Order
PPL - Unit 2
Arithmetic Expressions: Potentials for
Side Effects
PPL - Unit 2
Functional Side Effects
PPL - Unit 2
Referential Transparency
PPL - Unit 2
1-134
Overloaded Operators
PPL - Unit 2
1-135
Overloaded Operators (continued)
PPL - Unit 2
1-136
Type Conversions
PPL - Unit 2
1-137
Type Conversions: Mixed Mode
PPL - Unit 2
1-138
Explicit Type Conversions
PPL - Unit 2
1-139
Type Conversions: Errors in Expressions
• Causes
– Inherent limitations of arithmetic
e.g., division by zero
– Limitations of computer arithmetic
e.g. overflow
• Often ignored by the run-time system
PPL - Unit 2
1-140
Relational and Boolean Expressions
• Relational Expressions
– Use relational operators and operands of
various types
– Evaluate to some Boolean representation
– Operator symbols used vary somewhat among
languages (!=, /=, ~=, .NE., <>, #)
• JavaScript and PHP have two additional
relational operator, === and !==
- Similar to their cousins, == and !=, except that
they do not coerce their operands
PPL - Unit 2
1-141
Relational and Boolean Expressions
• Boolean Expressions
– Operands are Boolean and the result is Boolean
– Example operators
PPL - Unit 2
1-142
Relational and Boolean Expressions: No
Boolean Type in C
PPL - Unit 2
1-143
Short Circuit Evaluation
PPL - Unit 2
1-144
Short Circuit Evaluation (continued)
PPL - Unit 2
1-145
Assignment Statements
PPL - Unit 2
1-146
Assignment Statements: Conditional
Targets
• Conditional targets (Perl)
($flag ? $total : $subtotal) = 0
Which is equivalent to
if ($flag){
$total = 0
} else {
$subtotal = 0
}
PPL - Unit 2
1-147
Assignment Statements: Compound
Operators
a = a + b
is written as
a += b
PPL - Unit 2
1-148
Assignment Statements: Unary
Assignment Operators
• Unary assignment operators in C-based
languages combine increment and
decrement operations with assignment
• Examples
sum = ++count (count incremented, added to sum)
sum = count++ (count incremented, added to sum)
count++ (count incremented)
-count++ (count incremented then negated)
PPL - Unit 2
1-149
Assignment as an Expression
PPL - Unit 2
1-150
List Assignments
PPL - Unit 2
1-151
Mixed-Mode Assignment
PPL - Unit 2
1-152
Summary
• Expressions
• Operator precedence and associativity
• Operator overloading
• Mixed-type expressions
• Various forms of assignment
PPL - Unit 2
1-153
Statement-Level
Control Structures
• Introduction
• Selection Statements
• Iterative Statements
• Unconditional Branching
• Guarded Commands
• Conclusions
PPL - Unit 2
1-154
Levels of Control Flow
PPL - Unit 2
1-155
Control Structure
PPL - Unit 2
1-156
Selection Statements
PPL - Unit 2
1-157
Two-Way Selection Statements
• General form:
if control_expression
then clause
else clause
• Design Issues:
– What is the form and type of the control
expression?
– How are the then and else clauses specified?
– How should the meaning of nested selectors be
specified?
PPL - Unit 2
1-158
The Control Expression
PPL - Unit 2
1-159
Clause Form
• Java example
if (sum == 0)
if (count == 0)
result = 0;
else result = 1;
• Which if gets the else?
• Java's static semantics rule: else matches
with the nearest if
PPL - Unit 2
1-161
Nesting Selectors (continued)
PPL - Unit 2
1-162
Nesting Selectors (continued)
PPL - Unit 2
1-163
Nesting Selectors (continued)
• Python
if sum == 0 :
if count == 0 :
result = 0
else :
result = 1
PPL - Unit 2
1-164
Multiple-Way Selection Statements
PPL - Unit 2
1-165
Multiple-Way Selection: Examples
PPL - Unit 2
1-166
Multiple-Way Selection: Examples
PPL - Unit 2
1-167
Multiple-Way Selection: Examples
• C#
– Differs from C in that it has a static semantics
rule that disallows the implicit execution of
more than one segment
PPL - Unit 2
1-168
Multiple-Way Selection: Examples
• Ada
case expression is
when choice list => stmt_sequence;
…
when choice list => stmt_sequence;
[when others => stmt_sequence;]
end case;
PPL - Unit 2
1-170
Multiple-Way Selection: Examples
PPL - Unit 2
1-172
Multiple-Way Selection Using if
PPL - Unit 2
1-173
Iterative Statements
PPL - Unit 2
1-174
Counter-Controlled Loops
• A counting iterative statement has a loop
variable, and a means of specifying the
initial and terminal, and stepsize values
• Design Issues:
1. What are the type and scope of the loop
variable?
2. Should it be legal for the loop variable or loop
parameters to be changed in the loop body,
and if so, does the change affect loop control?
3. Should the loop parameters be evaluated only
once, or once for every iteration?
PPL - Unit 2
1-175
Iterative Statements: Examples
• FORTRAN 95 syntax
DO label var = start, finish [, stepsize]
• Stepsize can be any value but zero
• Parameters can be expressions
• Design choices:
1. Loop variable must be INTEGER
2. The loop variable cannot be changed in the loop, but the
parameters can; because they are evaluated only once, it
does not affect loop control
3. Loop parameters are evaluated only once
PPL - Unit 2
1-176
Iterative Statements: Examples
PPL - Unit 2
1-177
Iterative Statements: Examples
• Ada
for var in [reverse] discrete_range loop
...
end loop
• Design choices:
-Type of the loop variable is that of the discrete
range (A discrete range is a sub-range of an
integer or enumeration type).
- Loop variable does not exist outside the loop
-The loop variable cannot be changed in the loop,
but the discrete range can; it does not affect loop
control
- The discrete range is evaluated just once
• Cannot branch into the loop body
PPL - Unit 2
1-178
Iterative Statements: Examples
• C-based languages
for ([expr_1] ; [expr_2] ; [expr_3]) statement
-The expressions can be whole statements, or even
statement sequences, with the statements separated by
commas
– The value of a multiple-statement expression is the value of the
last statement in the expression
– If the second expression is absent, it is an infinite loop
• Design choices:
- There is no explicit loop variable
- Everything can be changed in the loop
- The first expression is evaluated once, but the other two
are evaluated with each iteration
PPL - Unit 2
1-179
Iterative Statements: Examples
PPL - Unit 2
1-180
Iterative Statements: Examples
• Python
for loop_variable in object:
-loop body
[else:
- else clause]
PPL - Unit 2
1-181
Iterative Statements: Logically-
Controlled Loops
PPL - Unit 2
1-182
Iterative Statements: Logically-
Controlled Loops: Examples
• C and C++ have both pretest and posttest
forms, in which the control expression can
be arithmetic:
while (ctrl_expr) do
loop body loop body
while (ctrl_expr)
• Java is like C and C++, except the control
expression must be Boolean (and the body
can only be entered at the beginning -- Java
has no goto
PPL - Unit 2
1-183
Iterative Statements: Logically-
Controlled Loops: Examples
PPL - Unit 2
1-184
Iterative Statements: User-Located Loop
Control Mechanisms
PPL - Unit 2
1-185
Iterative Statements: User-Located Loop
Control Mechanisms break and continue
PPL - Unit 2
1-186
Iterative Statements: Iteration Based on
Data Structures
• Number of elements of in a data structure
control loop iteration
• Control mechanism is a call to an iterator
function that returns the next element in
some chosen order, if there is one; else
loop is terminate
• C's for can be used to build a user-defined
iterator:
for (p=root; p==NULL; traverse(p)){
}
PPL - Unit 2
1-187
Iterative Statements: Iteration Based on
Data Structures (continued)
PHP
- current points at one element of the array
- next moves current to the next element
- reset moves current to the first element
• Java
- For any collection that implements the Iterator interface
- next moves the pointer into the collection
- hasNext is a predicate
- remove deletes an element
PPL - Unit 2
1-188
Iterative Statements: Iteration Based on
Data Structures (continued)
• Java 5.0 (uses for, although it is called foreach)
- For arrays and any other class that implements
Iterable interface, e.g., ArrayList
• Lua
– Lua has two forms of its iterative statement, one
like Fortran’s Do, and a more general form:
for variable_1 [, variable_2] in iterator(table) do
…
end
– The most commonly used iterators are pairs
and ipairs
PPL - Unit 2
1-190
Unconditional Branching
PPL - Unit 2
1-191
Guarded Commands
• Designed by Dijkstra
• Purpose: to support a new programming
methodology that supported verification
(correctness) during development
• Basis for two linguistic mechanisms for
concurrent programming (in CSP and Ada)
• Basic Idea: if the order of evaluation is not
important, the program should not specify
one
PPL - Unit 2
1-192
Selection Guarded Command
• Form
if <Boolean exp> -> <statement>
[] <Boolean exp> -> <statement>
...
[] <Boolean exp> -> <statement>
fi
• Semantics: when construct is reached,
– Evaluate all Boolean expressions
– If more than one are true, choose one non-
deterministically
– If none are true, it is a runtime error
PPL - Unit 2
1-193
Loop Guarded Command
• Form
do <Boolean> -> <statement>
[] <Boolean> -> <statement>
...
[] <Boolean> -> <statement>
od
• Semantics: for each iteration
– Evaluate all Boolean expressions
– If more than one are true, choose one non-
deterministically; then start loop again
– If none are true, exit loop
PPL - Unit 2
1-194
Guarded Commands: Rationale
PPL - Unit 2
1-195
Conclusion
PPL - Unit 2
1-196