0% found this document useful (0 votes)
77 views54 pages

CSC305 CHAPTER 2b

The document discusses language design principles, specifically describing syntax and semantics, type checking, and expressions and assignment statements. It covers: 1) Static type checking that is done at compile time to catch errors, with advantages of being less costly but reducing flexibility. 2) Different types of variables and data types in languages, including basic, constructed, primitive, composite, recursive, and user-defined types. 3) Scope rules and the differences between static and dynamic scoping. 4) Expressions and the components involved like operators, operands, order of evaluation, and type conversions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views54 pages

CSC305 CHAPTER 2b

The document discusses language design principles, specifically describing syntax and semantics, type checking, and expressions and assignment statements. It covers: 1) Static type checking that is done at compile time to catch errors, with advantages of being less costly but reducing flexibility. 2) Different types of variables and data types in languages, including basic, constructed, primitive, composite, recursive, and user-defined types. 3) Scope rules and the differences between static and dynamic scoping. 4) Expressions and the components involved like operators, operands, order of evaluation, and type conversions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

CHAPTER 2

LANGUAGE DESIGN PRINCIPLES


(PART 2)
DESCRIBING SYNTAX &
SEMANTIC
TYPE CHECKING
The compiler must perform static type checking.
Static type checking is done at the compile time.

Advantage Disadvantage
Less costly Reduced
programmer
flexibility
Example:
Compiler will report an error if operator is applied to
incompatible operand.

Example of type error:


If an integer value was passed to a function that expected
a float value
TYPE CHECKING
In most language, types either basic or constructed.
Basic types are the atomic types with no internal
structure such as boolean, integer, real, character,
subrange and enumerated.
Constructed types are arrays, records, sets, pointer,
function

Static and dynamic checking type


Checking done by compiler is static while if done at
runtime is dynamic.
TYPE CHECKING
STRONG TYPING
A strongly typed language is one in which each name
in a
program in the language has a single type associated
with it &
that type is known at compile time

A programming language is said to be strongly typed if


type
errors are always detected.
Example: ML
TYPE COMPATIBILITY
2 different types of compatibility methods:
 Name type compatibility
 2 variables have compatible types only if they are
defined in either the same declaration or in declarations
that use the same type name.
 Easy to implement but is highly restrictive

 Structure type compatibility


 variables have compatible types if their type has identical
structures
 More flexible but more difficult to implement
SCOPE
 The scope of a variable is the range of statements over
which it is visible:
Variable yyy is visible in statement st1 if yyy can be
referenced in st1.

 The scope rules of a language determine how occurrences


of names are associated with variables:
static scoping.
dynamic scoping.

 Two types of variables:


Local variables: declared inside the program unit/block.
Nonlocal variable: visible, but declared outside the
program unit.
STATIC SCOPE
 With static scope, a variable always refers to its top-level
environment. This is a property of the program text and
unrelated to the runtime call stack.

 Because matching a variable to its binding only requires


analysis of the program text, this type of scoping is
sometimes also called lexical scoping.

 Static scope is standard in modern functional languages


such as ML because it allows the programmer to reason as
if variable bindings are carried out by substitution.
STATIC SCOPE
•Introduced by Algol 60
Static scope •In static scoping, the scope of the
variable can be statically determined
(prior to execution)

•Languages in which subprograms


can be nested
2 categories of •Example: Ada, Javascript, PHP
Static scoped
languages: •Languages in which subprograms
cannot be nested
•Example: C-based languages
STATIC SCOPE : SUBPROGRAMS
DYNAMIC SCOPE
 With dynamic scope, each identifier has a global stack of
bindings.

 Introducing a local variable with name x pushes a binding


onto the global x stack (which may have been empty),
which is popped off when the control flow leaves the
scope.

 Evaluating x in any context always yields the top binding.


In other words, a global identifier refers to the identifier
associated with the most recent environment.

 Note that this cannot be done at compile time because the


binding stack only exists at runtime, which is why this type
DYNAMIC SCOPE
• It is based on the calling sequence of
subprograms, not on spatial relationship to each
other.
• The scope can only be determined at runtime

•Example of languages:
APL, SNOBOL4, Early version of LISP
STATIC vs DYNAMIC SCOPE
 Static scope: names are associated to variables based on
their textual layout (spatial).

 Dynamic Scope: names are associated to variables based on


calling sequences of program units (temporal)
 references to variables are connected to declarations by
searching back through the chain of subprogram calls
that forced execution to this point.
DATA TYPES
TYPES
Data types can be classified into two:
 Built in data types:
Primitive data type => 4 main types: int, real, boolean,
character
Composite data type
Homogeneous (array) and Heterogeneous (record
structures)
Grouped => fixed sized data types (arrays, strings, poiters,
structures, functions, list) and dynamic sized data types
(linked lists, stacks, queues)
Recursive data types – commonly used in fuctional and logic

 User defined data types


DATA TYPES :Primitive Data Types
 Data types that are not defined in terms of other types are called
primitive data types.

1. Numeric Types
a) Integer – the most common primitive numeric data types
C++ : (int, long), Pascal: (Integer, Longint), Java: (int, long)

b) Floating point – real numbers


C++ : (float, double), Pascal: (Real), Java: (float, double)

c) Decimal
- store a fixed number of decimal digits with decimal points
- the primary data type for COBOL
DATA TYPES :Primitive Data Types

2. Boolean Types

 The simplest of all data types


 Their range of values has only 2 elements: true & false
 Introduced in Algol60, often used to represent switches or
flags in programs
DATA TYPES :Primitive Data Types
3. Character types

 Character data are stored in computers as numeric codings.


 Traditionally, the most commonly used coding was the 8-
bit code ASCII (American Standard Code for Information
Interchange), which uses the values 0 to 127 to code 128
different characters.
 ISO 8859-1 is another 8-bit character code, but it allows
256 different characters.
 A 16-bit character set named Unicode includes the
characters from most of the world’s natural languages.
 Example: character A is equal to decimal 65 in ASCII code
DATA TYPES : Composite
DataTypes
 Sometimes called structured data type.
 Classified as :
1. Heterogeneous – elements are of different data types
such as records & structure
2. Homogeneous – elements are of the same type such as
arrays

 2 groups of composite data types:


1. Fixed-sized data types : arrays, string, pointers,
structures, functions & lists
2. Dynamic-sized data types : linked-list, stacks & queue
DATA TYPES : Recursive
DataTypes
 Sometimes called circular data types
 Have values that are invoked by itself
 Commonly used in the functional & logic programming
DATA TYPES :User definedTypes
1. Enumeration types
 Enumeration type provides a way of defining &
grouping collections named constants, which are
called enumeration constants
 Example: enum days {Mon, Tue, Wed, Thu, Fri, Sat,
Sun}

2. Subrange types
 A subragge type is a contiguous subsequence of an
ordinal type
 Example: 12..14
 Subrange types were introduced by Pascal & are
included in Ada
EXPRESSIONS & ASSIGNMENT
STATEMENTS
EXPRESSIONS

Expressions are the fundamental means of specifying


computations in a programming languages

Things to be addressed when writing expressions in


programming language:
 Operators & operands
 The order of evaluation
 The type checking and conversion
ARITHMETIC EXPRESSIONS
The purpose of an arithmetic expression is to specify
an arithmetic computation

Arithmetic expressions consists of:


√ Operators
√ Operands
√ Parentheses
√ Function calls
ARITHMETIC EXPRESSIONS
The operators can be:
Operator Explanation Example
Type
Unary Operators that works on single ++a
operand
Binary Operator that works on two a+b
operands

Ternary Operators that include a>b?
conditional evaluation Big = a : Big = b

Binary operators are infix => They appears between their


operands
ARITHMETIC EXPRESSIONS
Order of evaluation
Important to know in order to avoid the mistakes in executing
the expressions
Operator evaluation order: Typical precedence levels
1. Parentheses
Precedence 2. Unary operators
Associativity 3. **(if the lang. supports
it)
4. *,/
5. +,-
Precedence
define the order in which the operators of different
precedence levels are evaluated based on the hierarchy of
operator priorities
ARITHMETIC EXPRESSIONS
 Associativity
When an expression contains 2 adjacent occurrences of
operators with the same level of precedence, the question
of which operator is evaluated first is answered by the
associativity rules of the language
Will be used if operators have equal precedence
Left-to-right or right-to-left

Left
– leftmost occurrence is evaluated first
associativity

Right
– rightmost occurrence is evaluated first
associativity
ARITHMETIC EXPRESSIONS
 Parentheses:
Used by programmers to alter the precedence &
associativity rules by placing parentheses in expressions
A parenthesized part of an expression has precedence
over its adjacent unparenthesized parts
TYPE CONVERSIONS
 2 types:
1. Narrowing conversion
 Converts a value to a type that cannot store even
approximations of all the values of the original type
 Example: converting a real to int (from 3.5 to 3)
 Disadvantage: the value will change

2. Widening conversion
 Converts a value to a type that can include at least
approximations of all the values of the original type
 Example: converting an int to real (from 3 to 3.0)
 Advantage: safe as there is no value change
 Disadvantage: possible to have information loss &
incorrect calculation
TYPE CONVERSIONS
Conversion Explanation Advantages
Implicit It takes place when Improve the flexibility of a
conversion operands are language
(coercion) automatically - Limit the type checking by
converted into values automatically converting
of the correct data between operands, which are
type for an actually not the correct type
expression

Explicit Programmer can Improves the flexibility of


conversion explicitly convert the language
(casting) values of one data - Limits the type checking &
type into values of readability
another data type
RELATIONAL & BOOLEAN
EXPRESSIONS
Relational expressions:
A relational operator is an operator that compares
the values of its 2 operands
•A relational expression has 2 operands & one
relational operator
It returns a Boolean value based on the comparison

Common operators Common operands


< • Less than • Numeric values
> • greater than • expressions
= • equal to • ordinal types (primitive
!= • not equal to type)
<= • less than or equal to • string.
>= • greater than or equal to.
RELATIONAL & BOOLEAN
EXPRESSIONS
Boolean expressions:
Consist of:
1. Boolean variables (a = true or false )
2. Boolean constants (TRUE, FALSE)
3. Relational expressions (<, <=, >, <>, =)
4. Boolean operators (AND, OR, NOT)
ASSIGNMENT STATEMENTS
Assignment statement provides the mechanism by
which the user can dynamically change the bindings of
values to variables
The most common format is
<variable> <assignment operator> <expression>
Types of assignments:
1. Compound assignment
2. Unary assignment
3. Assignment as expressions
ASSIGNMENT STATEMENTS
Compound assignment operators:
 A compound assignment operator is a shorthand method of
specifying a commonly needed form of assignment
 Example: x += y equivalent to x = x + y

Unary assignment operators:


 ++ for increment
 -- for decrement

Assignments as expression
Example:
The value of xz =
is y = z to y, and then value of y
assigned
is assigned to x. Finally the value of x, y and z are
similar to each other.
MIXED-MODE ASSIGNMENT
Binary operators combine two expressions into a
single expression.

If the two input expressions are of different data types,


the expression is said to be a mixed mode expression.
the data type which appears furthest down in the table
will be the data type of the combined expression.

For example, an int plus a real produces a real.


STATEMENT- LEVEL CONTROL
STRUCTURE
INTRODUCTION
Control Statements / Control structure

 Used to modify the order of execution


 4 types of control statements:
1. Compound statements
2. Selection statements
3. Iterative statements
4. Unconditional branching
COMPOUND STATEMENTS
A collection of statements & executed in
sequential order that is from the beginning (first
statement) to the end (last statement)
Always written within delimiters such as
begin/end pair or brackets
{
pi = 3.141593;
circumference = 2. * pi * radius;
area = pi * radius * radius;
}
SELECTION STATEMENTS
Provides the means of choosing between multiple
possible execution paths
Can be categorized into 2 general categories:
1. Two-way selections – if…else

Multiple selection using if


2. Multiple selections – switch statement:
Is used when a
switch..case is
inadequate for
multiple selection
ITERATIVE STATEMENTS
An iterative statement is one that causes a statement or
collection of statements to be executed zero, one or
more times
2 styles can be applied to write an iterative statement:
bottom testing (pre-test) & top testing (post-test)
Divided into 3 categories:
1. Counter-controlled loops (Counting)
2. Logic-controlled loops (Logical)
3. A mixed controlled loops (Combination of both)
ITERATIVE STATEMENTS
1. Counter- controlled loops

Use the following features to control iteration:


i. A loop variable, to maintain the count
ii. A step size, to determine the amount by which the
loop variable is altered on each pass through the
loop
iii. An initial value for the loop variable
iv. A terminal value for the loop variable
ITERATIVE STATEMENTS
 The examples are:
 The Do statement of Fortran 95
 The Ada for statement
 The for statement of the C-based language

Loop Initial Terminal


variable value value
Step size

for (int x = 1; x < 10; x++)


cout<<++x<<‘ ‘;
ITERATIVE STATEMENTS
2. Logic- controlled loops
 Repetition control is based on Boolean expression
 Design is much simpler
Programmer has to decide whether the loop should be
pre-test (while loop) or post-test (do-while loop)
ITERATIVE STATEMENTS
User-located Loop Control Mechanism

 It allows a programmer to choose a location for loop control


other than the top or bottom of the loop
 Examples:
 C & C++ have unconditional unlabeled exits (break)
 Perl has last
 C & C++ include an unlabeled control statement; continue
 It is not a exit but rather a way to skip the rest of the
loop statements on the current iteration without
terminating the loop structure
ITERATIVE STATEMENTS
 Iteration based on data structure
Rather than have a counter or Boolean expression
controlled the iteration, these loop are controlled by the
number of elements a data structure

 A general data-based iteration statement uses a user-defined


data structure & a user-defined function to go through the
structure’s elements

 The iterator is called at the beginning of each iteration &


each time it is called, the iterator returns an elements from
a particular data structure in some specific order
UNCONDITIONAL BRANCHING
 An unconditional branch statement transfers execution
control to a specified place in the program
 aka goto
 The most powerful statement for controlling the flow of
execution of a program’s statements
 However, using the goto carelessly can lead to serious
problems
Advantage Disadvantage
The most flexible single Can easily obscure program
command for control structure, making software
execution difficult to understand &
maintain
GUARDED COMMANDS
New & different forms of selection & loop structures
suggested by Dijkstra

A guarded command is a statement, or list of statements, that


is "guarded" by a boolean expression.
For example:
x >= y -> max := x;
(guard) (command)

The idea being that the command cannot be executed unless


the guard evaluates to true.
SUBPROGRAM
FUNDAMENTALS OF
SUBPROGRAM
 General subprogram characteristics:
Each subprogram has a single entry point
Control always returns to the caller when the
subprogram execution terminates

 A subprogram header:
Specifies that the following syntactic unit is a
subprogram definition of some particular kind
Provides a name for the subprogram
May optionally specify a list of parameters
Example: void display (parameters)
FUNDAMENTALS OF
SUBPROGRAM
 The parameter profile:
 aka signature
 Contains the number, order & types of its formal parameter

 They are necessary when the compiler must translate a


subprogram call before it has seen that subprogram’s
definition

 Functions declarations are common in C & C++ programs,


where they are called prototypes
FUNDAMENTALS OF
SUBPROGRAM
 Data passed through parameters are accessed through
names that are local to the subprogram
 Parameter passing is more flexible than direct access to
nonlocal variables

 Actual parameters:
Are parameters in the subprogram call statements
Used to be bound to the formal parameters of the
subprogram
FUNDAMENTALS OF
SUBPROGRAM

 Keyword parameters:
The name of the formal parameters to which an actual
parameter is to be bound is specified with the actual
parameter
FUNDAMENTALS OF
SUBPROGRAM
 2 categories of subprograms:
 Procedures :
 Collections of statements that define parameterized
computations
 These computations are enacted by single call statement
 Functions:
 Functions structurally resemble procedures but are
semantically modeled on mathematical functions
 The value produced by a function’s execution is returned
to the calling code, effectively replacing the call itself
PARAMETER-PASSING
METHODS
Implementation models for parameter passing:
Pass-by-value
Pass-by-result
Pass-by-value-result
Pass-by-reference
Pass-by-name

You might also like