PPL Notes Unit 1 and 2
PPL Notes Unit 1 and 2
UNIT-I
1. Reasons for studying
2. Concepts of programming languages
3. Programming domains
4. Language Evaluation Criteria
5. Influences on Language design
6. Language categories
7. Programming Paradigms – Imperative, Object Oriented, functional Programming, and Logic
Programming.
8. Programming Language Implementation – Compilation and Virtual Machines
9. Programming environments.
UNIT-II
1. Elementary Data Types: Primitive data Types, Character String types, User Defined Ordinal Types, Array
types, Associative Arrays, Record Types, Union Types, Pointer and reference Type.
2. Expression and Assignment Statements: Arithmetic expression, Overloaded Operators, Type conversions,
Relational and Boolean Expressions, Short Circuit Evaluation, Assignment Statements, Mixed mode
Assignment.
3. Statement level Control Statements: Selection Statements, Iterative Statements, Unconditional Branching.
4. Subprograms: Fundamentals of Sub Programs, Design Issues for Subprograms, Local referencing
Environments, Parameter passing methods.
5. Abstract Data Types and Encapsulation Construct: Design issues for Abstraction, Parameterized Abstract
Data types, Encapsulation Constructs, Naming Encapsulations
1 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
UNIT – I
PRELIMINARY CONCEPTS
2 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Programming Domains
• Scientific applications
– In the early 40s computers were invented for scientific applications.
– The applications require large number of floating-point computations.
– Fortran was the first language developed scientific applications.
– ALGOL 60 was intended for the same use.
• Business applications
– The first successful language for business was COBOL.
– Produce reports, use decimal arithmetic numbers and characters.
– The arrival of PCs started new ways for businesses to use computers.
– Spreadsheets and database systems were developed for business.
• Artificial intelligence
– Symbolic rather than numeric computations are manipulated.
– Symbolic computation is more suitably done with linked lists than arrays.
– LISP was the first widely used AI programming language.
• Systems programming
– The O/S and all of the programming supports tools are collectively known as its
system software.
– Need efficiency because of continuous use.
• Scripting languages
– Put a list of commands, called a script, in a file to be executed.
– PHP is a scripting language used on Web server systems. Its code is embedded in
HTML documents. The code is interpreted on the server before the document is
3 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
– Special-purpose languages
+= 1
count
++
++count
– Although the last two statements have slightly different meaning from each
other and from the others, all four have the same meaning when used as stand-
alone expressions.
– Operator overloading where a single operator symbol has more than one meaning.
– Although this is a useful feature, it can lead to reduced readability if users are
allowed to create their own overloading and do not do it sensibly.
• Orthogonality
4 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
• Control Statements
– It became widely recognized that indiscriminate use of goto statements severely
reduced program readability.
– Ex: Consider the following nested loops
written in C while (incr < 20)
{
while (sum <= 100
{
sum += incr;
}
incr++;
loop1:
out; loop2:
go to
5 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
loop2; next:
incr++;
go to loop1:
out:
– Basic and Fortran in the early 70s lacked the control statements that allow
strong restrictions on the use of gotos, so writing highly readable programs in
those languages was difficult.
– Since then, languages have included sufficient control structures.
– The control statement design of a language is now a less important factor in
readability than it was in the past.
Syntax Considerations
– The syntax of the elements of a language has a significant effect on readability.
– The following are examples of syntactic design choices that affect readability:
• Identifier forms: Restricting identifiers to very short lengths detracts from
readability. ANSI BASIC (1978) an identifier could consist only of a
single letter of a single letter followed by a single digit.
• Special Words: Program appearance and thus program readability are
strongly influenced by the forms of a language’s special words. Ex: while,
class, for. C uses braces for pairing control structures. It is difficult to
determine which group is being ended. Fortran 95 allows programmers to
use special names as legal variable names.
• Form and Meaning: Designing statements so that their appearance
at least partially indicates their purpose is an obvious aid to
readability.
• Semantic should follow directly from syntax, or form.
• Ex: In C the use of static depends on the context of its appearance.
6 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Writability
It is a measure of how easily a language can be used to create programs for a chosen
problem domain.
Most of the language characteristics that affect readability also affect writability.
• Simplicity and orthogonality
– A smaller number of primitive constructs and a consistent set of rules for
combining them is much better than simply having a large number of primitives.
• Support for abstraction
– Abstraction means the ability to define and then use complicated structures or
operations in ways that allow many of the details to be ignored.
– A process abstraction is the use of a subprogram to implement a sort algorithm
that is required several times in a program instead of replicating it in all places
where it is needed.
• Expressivity
– It means that a language has relatively convenient, rather than cumbersome,
ways of specifying computations.
Reliability
A program is said to be reliable if it performs to its specifications under all conditions.
• Type checking: is simply testing for type errors in a given program, either by the
compiler or during program execution.
– The earlier errors are detected, the less expensive it is to make the required
repairs. Java requires type checking of nearly all variables and expressions at
compile time.
• Exception handling: the ability to intercept run-time errors, take corrective measures,
and then continue is a great aid to reliability.
• Aliasing: it is having two or more distinct referencing methods, or names, for the same
memory cell.
– It is now widely accepted that aliasing is a dangerous feature in a language.
7 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
8 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Programming methodologies
• 1950s and early 1960s: Simple applications; worry about machine efficiency
• Late 1960s: People efficiency became important; readability, better control structures
– Structured programming
– Top-down design and step-wise refinement
• Late 1970s: Process-oriented to data-oriented
– data abstraction
• Middle 1980s: Object-oriented programming
Language Categories
• Imperative
– Central features are variables, assignment statements, and iteration
– C, Pascal
• Functional
– Main means of making computations is by applying functions to given parameters
– LISP, Scheme
• Logic
– Rule-based
– Rules are specified in no special order
– Prolog
• Object-oriented
– Encapsulate data objects with processing
9 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Programming Environments
• The collection of tools used in software development
• UNIX
– An older operating system and tool collection
• Borland JBuilder
– An integrated development environment for Java
• Microsoft Visual Studio.NET
– A large, complex visual environment
– Used to program in C#, Visual BASIC.NET, Jscript, J#, or C++
Genealogy of common high-level programming languages
2. Implementors
Functional Programming
Q Describe Functional Programming. Enlist its features. Also list the commonly used functional
10 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Logical Programming
Q. Describe Logical Programming. Enlist its features. Also list the commonly used Logical
programming languages. (April 23) (April 22) [6]
Q. Comparisons between functional programming and logic programming. (oct 22) [5]
Answer: Logic programming is a computer programming paradigm where program statements
express facts and rules about problems within a system of formal logic.
11 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
UNIT-II
DATA TYPES
Data type Definition:
Data Types:
• Primitive
• Structured
Integer Types:
– Python has an integer type and a long integer which can get as big as it needs to.
1. Representing Integers:
– Ones complement
12 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
• Sign bit
• Ones complement
Twos Complement:
• Precision is the accuracy of the fractional part of a value, measured as the number of bits
• Range is a combination of the range of fractions and, more important, the range of exponents.
13 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
• We can convert the decimal number to base 2 just as we did for integers
– fixed number of bits for the whole and fractional parts severely limits the range of
values we can represent
• Use a fixed number of bits for the exponent which is offset to allow for negative exponents
– float
– double
• Some scripting languages only have one kind of number which is a floating point type
14 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
– Essential to COBOL
• Advantage: accuracy
C# decimal Type:
• 128-bit representation
– no roundoff error
• Boolean
– Range of values: two elements, one for “true” and one for “false”
– A Boolean value could be represented by a single bit, but because a single bit of
memory cannot be accessed efficiently on many machines, they are often stored in the
smallest efficiently addressable cell of memory, typically a byte.
• Character
• Rational (Scheme)
15 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Character Strings :
• Character string constants are used to label output, and the input and output of all kinds of data
are often done in terms of strings.
• Operations:
– Assignment and copying
– Comparison (=, >, etc.)
– Concatenation
– Substring reference
– Pattern matching
- A substring reference is a reference to a substring of a given string. Substring references are discussed
in the more general context of arrays, where the substring references are called slices.
• Design issues:
• C and C++
– Not primitive
Char Mystring[4]={‘E’,’x’,’a’,’m’};
– Primitive
• Java
16 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
String Implementation
– the string length is not fixed hence storage may grow or shrink dynamically.
• These data types are defined by the programmer with the help if primitive data type.
17 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
– integer
– char
– boolean
Enumeration Types:
• All possible values, which are named constants, are provided in the definition
• A way of defining and grouping collections of named constants, which are called enumeration constants.
C example:
• Design issues
– duplication of names
– coercion rules
Ex:
typedef enum weekday {Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}
weekday;
18 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
– toString and valueOf are overridden to make input and output easier
System.out.println (season);
// prints WINTER
Example:
• Ada’s design:
Day1: Days;
Day2: Weekday;
Day2:= Day1;
Evaluation
Subrange types enhance readability by making it clear to readers that variables of subtypes can store only
certain ranges of values. Reliability is increased with subrange types, because assigning a value to a
subrange variable that is outside the specified range is detected as an error, either by the compiler (in the
19 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
case of the assigned value being a literal value) or by the run-time system (in the case of a variable or
expression). It is odd that no contemporary language except Ada has subrange types.
subscript values to an element in the aggregate. Indeed, arrays are sometimes called finite
mappings. Symbolically, this mapping can be shown as
array_name(subscript_value_list) → element
Subscript Bindings and Array Categories
• The binding of the subscript type to an array variable is usually static, but the subscript value
ranges are sometimes dynamically bound.
• There are five categories of arrays, based on the binding to subscript ranges, the binding to
storage, and from where the storage is allocated.
• A static array is one in which the subscript ranges are statically bound and storage allocation
is static (done before run time).
The advantage of static arrays is efficiency: No dynamic allocation or deallocation
is required.
The disadvantage is that the storage for the array is fixed for the entire execution time
of the program.
• A fixed stack-dynamic array is one in which the subscript ranges are statically bound, but
the allocation is done at declaration elaboration time during execution.
The advantage of fixed stack-dynamic arrays over static arrays is space efficiency
The disadvantage is the required allocation and deallocation time
• A stack-dynamic array is one in which both the subscript ranges and the storage allocation
20 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
are dynamically bound at elaboration time. Once the subscript ranges are bound and the storage
is allocated, however, they remain fixed during the lifetime of the variable.
The advantage of stack-dynamic arrays over static and fixed stack-dynamic arrays is
flexibility
• A fixed heap-dynamic array is similar to a fixed stack-dynamic array, in that the subscript ranges
and the storage binding are both fixed after storage is allocated
The advantage of fixed heap-dynamic arrays is flexibility—the array’s size always fits
the problem.
The disadvantage is allocation time from the heap, which is longer than allocation
time from the stack.
• A heap-dynamic array is one in which the binding of subscript ranges and storage allocation
is dynamic and can change any number of times during the array’s lifetime.
The advantage of heap-dynamic arrays over the others is flexibility:
The disadvantage is that allocation and deallocation take longer and may happen many
times during execution of the program.
Array Initialization
Some languages provide the means to initialize arrays at the time their storage is allocated.
An array aggregate for a single-dimensioned array is a list of literals delimited by parentheses and slashes.
For example, we could have
Integer, Dimension (3) :: List = (/0, 5, 5/)
In the C declaration
int list [] = {4, 5, 7, 83};
These arrays can be initialized to string constants, as in
char name [] = "freddie";
Arrays of strings in C and C++ can also be initialized with string literals. In this case, the array is one of
pointers to characters.
For example,
char *names [] = {"Bob", "Jake" ,"Darcie"};
In Java, similar syntax is used to define and initialize an array of references to String
objects. For example,
String[] names = ["Bob", "Jake", "Darcie"];
Ada provides two mechanisms for initializing arrays in the declaration statement: by listing them in the
order in which they are to be stored, or by directly assigning them to an index position using the =>
operator, which in Ada is called an arrow.
For example, consider the following:
21 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
when multi dimensioned arrays are actually arrays of arrays. For example, a matrix would appear as an
array of single-dimensioned arrays.
For example,
myArray[3][7]
Slices
A slice of an array is some substructure of that array.
For example, if A is a matrix, then the first row of A is one possible slice, as are the last row and the first
column. It is important to realize that a slice is not a new data type. Rather ,it is a mechanism for
referencing part of an array as a unit.
Evaluation
Arrays have been included in virtually all programming languages
Implementation of Array Types
Implementing arrays requires considerably more compile-time effort than does implementing primitive
types. The code to allow accessing of array elements must be generated at compile time. At run time, this
code must be executed to produce element addresses. There is no way to pre compute the address to be
accessed by a reference such as
list [k]
A single-dimensioned array is implemented as a list of adjacent memory cells. Suppose the array list is
defined to have a subscript range lower bound of 0. The access function for list is often of the form
address
( list [k] ) = address (list [0] ) + k * element_size where the first operand of the addition is the
constant part of the access function, and the second is the variable part .
22 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
If the element type is statically bound and the array is statically bound to storage, then the value of the
constant part can be computed before run time. However, the addition and multiplication operations must
be done at run time.
The generalization of this access function for an arbitrary lower bound is address (list[k]) = address
( list [lower_bound]) + ( (k - lower_bound) * element_size)
Associative Arrays
An associative array is an unordered collection of data elements that are indexed by an equal number of
values called keys. In the case of non-associative arrays, the indices never need to be stored (because of
their regularity). In an associative array, however, the user-defined keys must be stored in the structure.
So each element of an associative array is in fact a pair of entities, a key and a value. We use Perl’s
design of associative arrays to illustrate this data structure. Associative arrays are also supported directly
by
23 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Python, Ruby, and Lua and by the standard class libraries of Java, C++, C#, and F#. The only design issue
that is specific for associative arrays is the form of references to their elements.
Structure and Operations
In Perl, associative arrays are called hashes, because in the implementation their elements are stored and
retrieved with hash functions. The namespace for Perl hashes is distinct: Every hash variable name must
begin with a percent sign (%). Each hash element consists of two parts: a key, which is a string, and a
value, which is a scalar (number, string, or reference). Hashes can be set to literal values with the
assignment statement, as in
%salaries = ("Gary" => 75000, "Perry" => 57000,
"Mary" => 55750, "Cedric" => 47850);
Recall that scalar variable names begin with dollar signs
($). For example,
$salaries {"Perry"} = 58850;
A new element is added using the same assignment statement form. An element can be removed from the
hash with the delete operator, as in
Delete $salaries{"Gary"};
Record Types
A record is an aggregate of data elements in which the individual elements are identified by names and
accessed through offsets from the beginning of the structure. There is frequently a need in programs to
model a collection of data in which the individual elements are not of the same type or size. For example,
information about a college student might include name, student number, grade point average, and so
forth. A data type for such a collection might use a character string for the name, an integer for the student
number, a floating point for the grade point average, and so forth. Records are designed for this kind of
need.
The following design issues are specific to records:
• What is the syntactic form of references to fields?
• Are elliptical references allowed?
Definitions of Records
The fundamental difference between a record and an array is that record elements, or fields, are not
referenced by indices. Instead, the fields are named with identifiers, and references to the fields are made
using these identifiers The COBOL form of a record declaration, which is part of the data division of a
COBOL program, is illustrated in the following example:
01 EMPLOYEE-RECORD.
02 EMPLOYEE-NAME.
24 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
The fields of records are stored in adjacent memory locations. But because the sizes of the fields are not
necessarily the same, the access method used for arrays is not used for records. Instead, the offset
address, relative to the beginning of the record, is associated with each field. Field accesses are all
handled using these offsets. The compile-time descriptor for a record has the general form shown in
Figure 6.7. Run-time descriptors for records are unnecessary
25 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Union Types
A union is a type whose variables may store different type values at different times during program
execution. As an example of the need for a union type, consider a table of constants for a compiler, which
is used to store the constants found in a program being compiled. One field of each table entry is for the
value of the constant. Suppose that for a particular language being compiled, the types of constants were
integer, floating point, and Boolean. In terms of table management, it would be convenient if the same
location, a table field, could store a value of any of these three types. Then all constant values could be
addressed in the same way. The type of such a location is, in a sense, the union of the three value types it
can store.
Design Issues
The problem of type checking union types, leads to one major design issue. The other fundamental
question is how to syntactically represent a union. In some designs, unions are confined to be parts
of record structures, but in others they are not. So, the primary design issues that are particular to union
types are the following:
• Should type checking be required? Note that any such type checking must be dynamic.
• Should unions be embedded in records?
Unions are implemented by simply using the same address for every possible variant. Sufficient storage
for the largest variant is allocated. The tag of a discriminated union is stored with the variant in a record
like structure. At compile time, the complete description of each variant must be stored. This can be done
by associating a case table with the tag entry in the descriptor. The case table has an entry for each
variant, which points to a descriptor for that particular variant. To illustrate this arrangement, consider
the following Ada example:
type Node (Tag : Boolean) is
record
case Tag is
when True => Count : Integer;
when False => Sum : Float;
26 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
end case;
end record;
The descriptor for this type could have the form shown in Figure
– range of values that consists of memory addresses plus a special value, nil
Pointer Operations:
• Dereferencing yields the value stored at the location represented by the pointer’s value
j = *ptr
27 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Pointer Problems:
28 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Float stuff[100];
Float *p;
p = stuff;
Reference Types:
• C++ includes a special kind of pointer type called a reference type that is used primarily for
formal parameters
• Java extends C++’s reference variables and allows them to replace pointers entirely
Evaluation of Pointers:
• Pointers are like goto's--they widen the range of cells that can be accessed by a variable
• Pointers or references are necessary for dynamic data structures--so we can't design a language
without them
• A machine consists of
29 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
complicated
Names:
– Maximum length?
Length of Names:
• Language examples:
– FORTRAN I: maximum 6
– COBOL: maximum 30
• Real VarName (Real is a data type followed with a name, therefore Real is
30 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
a keyword)
31 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Variables:
– Name
– Address
– Value
– Type
– Lifetime
– Scope
Variable Attributes:
• Type - allowed range of values of variables and the set of defined operations
Value - the contents of the location with which the variable is associated (r-value
• Load time -- bind a FORTRAN 77 variable to a memory cell (or a C static variable)
• Runtime -- bind a nonstatic local variable to a memory cell
32 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
• A binding is static if it first occurs before run time and remains unchanged throughout
program execution.
• A binding is dynamic if it first occurs during execution or can change during execution of the
program
Type Binding:
– 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 )
Type Checking
• Generalize the concept of operands and operators to include subprograms and assignments
• Type checking is the activity of ensuring that the operands of an operator are of compatible types
Compatible type :
It is one that is either legal for the operator, or is allowed under language rules to be
implicitly converted, by compiler- generated code, to a legal type
• If all type bindings are static, nearly all type checking can be static (done at compile time)
• If type bindings are dynamic, type checking must be dynamic (done at run time)
– Advantage: allows the detection of misuse of variables that result in type errors
33 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
– C and C++
– Ada is almost
– Java is similar
Strong Typing:
Advantage of strong typing: allows the detection of the misuses of variables that result in type
errors
Language examples:
FORTRAN 77 is not: parameters, EQUIVALENCE
Pascal is not: variant records
C and C++ are not: parameter type checking can be avoided; unions are not
type checked
Ada is, almost (UNCHECKED CONVERSION is loophole)
(Java is similar)
Coercion rules strongly affect strong typing--they can weaken it considerably (C+ versus Ada)
Although Java has just half the assignment coercions of C++, its strong typing is
still far less effective than that of Ada
Type Compatibility
Our concern is primarily for structured types
Def: Name type compatibility means the two variables have compatible types if
they are in either the same declaration or in declarations that use the same type
name
34 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Are two record types compatible if they are structurally the same but use
different field names?
Are two array types compatible if they are the same except that the
subscripts are different?
(e.g. [1..10] and [0..9])
Are two enumeration types compatible if their components are
spelled differently?
With structural type compatibility, you cannot differentiate between types
of the same structure (e.g. different units of speed, both float)
Named Constants
⚫ Def: A named constant is a variable that is bound to a value only when it is
bound to storage
⚫ Advantages: readability and modifiability
⚫ Used to parameterize programs
The binding of values to named constants can be either static (called
manifest constants) or dynamic
Languages:
Pascal: literals only
FORTRAN 90: constant-valued expressions
Ada, C++, and Java: expressions of any kind
Variable Initialization
Def: The binding of a variable to a value at the time it is bound to storage is
called initialization
Initialization is often done on the declaration statement
e.g., Java
int sum = 0;
Coercion:
• Java's strong typing is still far less effective than that of Ada
35 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
List = 17.3;
• But …
• The lifetime of a variable is the time during which it is bound to a particular memory cell
• Depending on the language, allocation can be either controlled by the programmer or done
automatically
Variable Scope:
• The nonlocal variables of a program unit are those that are visible but not declared there
• The scope rules of a language determine how references to names are associated with variables
• Scope and lifetime are sometimes closely related, but are different concepts
Static Scope:
• To connect a name reference to a variable, you (or the compiler) must find the declaration
36 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
• Search process: search declarations, first locally, then in increasingly larger enclosing scopes,
until one is found for the given name Enclosing static scopes (to a specific scope) are called its
static ancestors; the nearest static ancestor is called a static parent
• Variables can be hidden from a unit by having a "closer" variable with the same name
• C++, Java and Ada allow access to some of these "hidden" variables
– In Ada: unit.name
A calls C and D
B calls A and E
• Suppose the spec is changed so that D must now access some data in B
• Solutions:
– Put D in B (but then C can no longer call it and D cannot access A's variables)
– Move the data from B that D needs to MAIN (but then all procedures can access them)
Dynamic Scope:
• Based on calling sequences of program units, not their textual layout (temporal versus spatial)
• References to variables are connected to declarations by searching back through the chain
of subprogram calls that forced execution to this point
• Static scoping
37 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
– Reference to x is to MAIN's x
• Dynamic scoping
– Reference to x is to SUB1's x
– Advantage: convenience
Referencing Environments:
• The referencing environment of a statement is the collection of all names that are visible in the
statement
• In a static-scoped language, it is the local variables plus all of the visible variables in all of the
enclosing scopes
Expressions and
Statements Arithmetic
Expressions:
• An operator can be unary, meaning it has a single operand, binary, meaning it has two operands,
or ternary, meaning it has three operands.
• In most programming languages, binary operators are infix, which means they appear between
their operands.
• One exception is Perl, which has some operators that are prefix, which means they precede their
operands.
• An implementation of such a computation must cause two actions: fetching the operands,
usually from memory, and executing arithmetic operations on those operands.
38 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
– operators
– operands
– parentheses
– function calls
– unary -, !
• A binary operator has two operands
– +, -, *, /, %
Conditional Expressions:
• Precedence rules define the order in which “adjacent” operators of different precedence levels
are evaluated
• Typical precedence levels
– parentheses
– unary operators
– ** (if the language supports it)
– *, /
+, -
39 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
• Associativity rules define the order in which adjacent operators with the same precedence
level are evaluated
2. Constants: sometimes a fetch from memory; sometimes the constant is in the machine
language instruction
• Functional side effects: when a function changes a two-way parameter or a non-local variable
• Problem with functional side effects:
– When a function referenced in an expression alters another operand of the expression;
e.g., for a parameter change:
a = 10;
/* assume that fun changes its parameter */
b = a + fun(a);
40 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
• Use of an operator for more than one purpose is called operator overloading
• Some are common (e.g., + for int and float)
• Some are potential trouble (e.g., * in C and C++)
– Loss of compiler error detection (omission of an operand should be a detectable error)
– Some loss of readability
– Can be avoided by introduction of new symbols (e.g., Pascal’s div for integer division)
Type Conversions
• A narrowing conversion converts an object to a type that does not include all of the values of the
original type
Errors in Expressions:
• Causes
– Inherent limitations of arithmetic e.g., division by zero, round-off errors
– Limitations of computer arithmetic e.g. overflow
41 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
.OR .or || or
.NOT .not ! not
No Boolean Type in C:
postfix ++, --
*,/,%
binary +,
=, !=
&&
42 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
||
Index++;
– When index=length, LIST [index] will cause an indexing problem (assuming LIST has
length -1 elements)
Mixed-Mode Assignment:
int a, b;
float c;
c = a / b;
Assignment Statements:
• = can be bad when it is overloaded for the relational operator for equality
Compound Assignment:
43 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
• Example
a=a+b
is written as
a += b
• Unary assignment operators in C-based languages combine increment and decrement operations
with assignment
Assignment as an Expression:
• In C, C++, and Java, the assignment statement produces a result and can be used as operands
• An example:
While ((ch = get char ())!= EOF){…}
ch = get char() is carried out; the result (assigned to ch) is used in the condition for the while
statement
Control Structure
44 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Selection Statements
• A selection statement provides the means of choosing between two or more paths of execution
• Two general categories:
–Two-way selectors
–Multiple-way selectors
• 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?
• If the then reserved word or some other syntactic marker is not used to introduce the then clause, the
control expression is placed in parentheses
• In C89, C99, Python, and C++, the control expression can be arithmetic
• In languages such as Ada, Java, Ruby, and C#, the control expression must be Boolean
Clause Form
• In many contemporary languages, the then and else clauses can be single statements or
compound statements
• In Perl, all clauses must be delimited by braces (they must be compound)
Nesting Selectors
45 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
• 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
Nesting Selectors (continued)
• To force an alternative semantics, compound statements may be
used: if (sum == 0) {
if (count == 0)
result = 0;
}
else result = 1;
• The above solution is used in C, C++, and C#
• Perl requires that all then and else clauses to be compound
• Statement sequences as clauses:
Ruby if sum == 0 then
if count == 0 then
result = 0
else
result = 1
end
end
•Python
if sum == 0 :
if count == 0 :
result = 0
else :
result = 1
46 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
…
when choice list => stmt_sequence;
when others => stmt_sequence;]
end case;
• More reliable than C‘s switch (once a stmt_sequence execution is completed, control is passed to
the first statement after the case statement
• Ada design choices:
47 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Iterative Statements
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:
• What are the type and scope of the loop variable?
• What is the value of the loop variable at loop termination?
• 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?
• Should the loop parameters be evaluated only once, or once for every iteration?
48 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
• 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
• 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
49 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
• 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
•C++ differs from C in two ways:
•The control expression can also be Boolean
•The initial expression can include variable definitions (scope is from the definition to the end of the loop
body)
•Java and C#
–Differs from C++ in that the control expression must be Boolean
Iterative Statements: Logically-Controlled Loops
•Repetition control is based on a Boolean expression
•Design issues:
–Pretest or posttest?
–Should the logically controlled loop be a special case of the counting loop statement or a separate
statement?
50 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
51 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
• 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
Guarded Commands: Rationale
• Connection between control statements and program verification is intimate
•Verification is impossible with goto statements
•Verification is possible with only selection and logical pretest loops
•Verification is relatively simple with only guarded commands
SUB PROGRAMS
Basic Definitions:
52 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Actual/Formal Param
Positional
Keyword
Sort (List => A, Length => N);
For named association:
Advantage: order is irrelevant
parameter’s names
Sort (List => A, Length => N);
53 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Example, in Ada:
54 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
o Allocation/deallocation time
o Indirect addressing
o Subprograms cannot be history sensitive
o Static locals are the opposite
Parameters and Parameter Passing:
• Pass-by-value
• Pass-by-result
• Pass-by-value-result
• Pass-by-reference
• Pass-by-name
Models of Parameter Passing
Pass-By-Value
in mode
Either by physical move or access path
Disadvantages of access path method: Must write-protect in the called subprogram, Accesses cost
more (indirect addressing)
55 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
...
sub1(x, x);
Pass-By-Value-Result
inout mode
Disadvantages:
Those of pass-by-result
Those of pass-by-value
Pass-By-Reference
inout mode
Disadvantages:
Slower accesses can allow aliasing: Actual parameter collisions: sub1(x, x); Array element
collisions: sub1(a[i], a[j]); /* if i = j */ Collision between formals and globals Root cause of all of
56 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
these is: The called subprogram is provided wider access to non locals than is necessary
Pass-by-value-result does not allow these aliases (but has other problems!)
Pass-By-Name multiple modes By textual substitution ,Formals are bound to an access method at
the time of the call, but actual binding to a value or address takes place at the time of a reference or
assignment
Resulting semantics:
Pass-By-Name Example 2
• Assume k is a global variable
procedure sub1(x: int; y: int; z: int);
begin
k := 1;
y := x;
k := 5;
z := x;
end;
sub1(k+1, j, i);
Disadvantages of Pass-By-Name
FORTRAN, Before 77, pass-by-reference 77—scalar variables are often passed by value result
57 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
C++: Like C, but also allows reference type parameters, which provide the efficiency of pass-by-
reference with in-mode semantics
Ada
All three semantic modes are available If out, it cannot be referenced If in, it cannot be assigned
Java Like C++, except only references
ALGOL 60 and most of its descendants use the runtime stack Value—copy it to the stack; references are
indirect to the stack Result—sum, Reference—regardless of form, put the address in the stack
Name:
Run-time resident code segments or subprograms evaluate the address of the parameter Called for each
reference to the formal, these are called thunks Very expensive, compared to reference or value-result
Simple variables are passed by copy (valueresult) Structured types can be either by copy or reference
This can be a problem, because Aliasing differences (reference allows aliases, but value-result does not)
Procedure termination by error can produce different actual parameter results Programs with such errors
are “erroneous”
58 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
If a multidimensional array is passed to a subprogram and the subprogram is separately compiled, the
compiler needs to know the declared size of that array to build the storage mapping function
C and C++
Programmer is required to include the declared sizes of all but the first subscript in the actual parameter ,
This disallows writing flexible subprograms Solution: pass a pointer to the array and the sizes of the
dimensions as other parameters; the user must include the storage mapping function, which is in terms of
the size
Ada
END
Efficiency
One-way or two-way
These two are in conflict with one another!
Good programming => limited access to
variables, which means one-way whenever possible
Efficiency => pass by reference is fastest way to pass structures of significant size Also,
functions should not allow reference Parameters
Subprograms As Parameters: Issues
59 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Early Pascal and FORTRAN 77 do not Later versions of Pascal, Modula-2, and FORTRAN 90 do Ada
does not allow subprogram parameters C and C++ - pass pointers to functions; parameters can be type
checked
Possibilities:
It is that of the subprogram that passed it (ad hocbinding, never been used)
For static-scoped languages, deep binding is most natural
Overloading
An overloaded subprogram is one that has the same name as another subprogram in the same referencing
environment C++ and Ada have overloaded subprograms built-in, and users can write their own
overloaded subprograms
Generic Subprograms
1. A generic or polymorphic subprogram is one that takes parameters of different types on different
activations Overloaded subprograms provide ad hoc polymorphism
2. A subprogram that takes a generic parameter that is used in a type expression that describes the
type of the parameters of the subprogram provides parametric polymorphism
3. See Ada generic and C++ template examples in text
4. Independent compilation is compilation of some of the units of a program separately from the rest
of the program, without the benefit of interface information
5. Separate compilation is compilation of some of the units of a program separately from the rest of the
program, using interface information to check the correctness of the interface between the two parts
Language Examples:
60 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Functions
Design Issues:
61 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
The nonlocal variables of a subprogram are those that are visible but not declared in the subprogram
Global variables are those that may be visible in all of the subprograms of a program
FORTRAN COMMON
Static scoping
External declarations: C
Users can further overload operators in C++ and Ada not carried over into Java)
is
62 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
sum : Integer := 0;
begin
end loop;
return sum;
end "*";
Coroutines:
Coroutine is a subprogram that has multiple entries and controls them itself Also called symmetric
control A coroutine call is named a resume. The first resume of a coroutine is to its beginning, but
subsequent calls enter at the point just after the last executed statement in the coroutine. Typically,
coroutines repeatedly resume each other, possibly forever. Coroutines provide quasiconcurrent
execution of program units (the coroutines) Their execution is interleaved, but not overlapped
63 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
- Nearly all programming languages designed since 1980 have supported data abstraction with some
kind of module
Encapsulation:
- Original motivation:
2. Some means of partial compilation (compilation units that are smaller than the whole program)
- Obvious solution: a grouping of subprograms that are logically related into a unit that can be
separately compiled
64 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
2. FORTRAN 77 and C - Files containing one or more subprograms can be independently compiled
3. FORTRAN 90, C++, Ada (and other contemporary languages) - separately compliable modules
Definitions: An abstract data type is a user-defined datatype that satisfies the following two conditions:
Definition 1: The representation of and operations of objects of the type are defined in a single
syntactic unit; also, other units can create objects of the type.
Definition 2: The representation of objects of the type is hidden from the program units that use
these objects, so the only operations possible are those provided in the type's definition.
Advantage of Restriction 1:
Advantage of Restriction 2:
- Reliability--by hiding the data representations, user code cannot directly access
objects of the type. User code cannot depend on the representation, allowing the representation to
be changed without affecting user code.
- User-defined abstract data types must have the same characteristics as built-in abstract data
types
2. A method of making type names and subprogram headers visible to clients, while hiding
actual definitions.
3. Some primitive operations must be built into the language processor (usually just
assignment and comparisons for equality and inequality)
- Some operations are commonly needed, but must be defined by the type designer
65 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
Language Examples:
1. Simula 67
2. Ada
- Information Hiding
- Hidden types are named in the spec package in, as in:
- Representation of an exported hidden type is specified in a special invisible (to clients) part
of the spec package (the private clause), as in:
package … is
type NODE_TYPE is
record
end record;
66 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
…
A spec package can also define unhidden type simply by providing the representation outside a private clause
1. The compiler must be able to see the representation after seeing only the spec package (the
compiler can see the private clause)
2. Clients must see the type name, but not the representation (clients cannot see the private clause)
• C++, Ada, Java 5.0, and C# 2005 provide support for parameterized ADTs
Parameterized ADTs in Ada
• Ada Generic Packages
–Make the stack type more flexible by making the element type and the size of the stack generic
generic
Max_Size: Positive;
type Elem_Type is private;
package Generic_Stack is
Type Stack_Type is limited private;
function Top(Stk: in out StackType) return Elem_type;
…
end Generic_Stack;
Package Integer_Stack is new Generic_Stack(100,Integer);
Package Float_Stack is new Generic_Stack(100,Float);
67 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
};
…
}
stack stk(100);
• The stack element type can be parameterized by making the class a template
class template <class Type>
class stack {
private:
Type *stackPtr;
const int maxLen;
int topPtr;
public:
stack() {
stackPtr = new Type[100];
maxLen = 99;
topPtr = -1;
}
…
}
68 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)
lOMoARcPSD|53449593
69 ASMITA S GAIKWAD
Downloaded by Harshad Pakhale (learntech2215@gmail.com)