9.2 Fundamentals of subprograms
- allow process abstractions
- each has a single entry point.
- the calling program unit is suspended during the execution of the call subprogram.
- parameters are a way of giving a subprograms access to the data they are to process
there are two types of subprograms - function and sub procedures
A Sub procedure is
a separate procedure that can take arguments, perform a series of
statements, and change the value of its arguments, it doesn't require to return a value, but it cannot be used in an expression. (expressed with void in C#)
A Function procedure, is a procedure that can take arguments, perform a series of
statements, and change the value of its arguments, but it also must return a value and it can be used
in an expression.
- local variables = Variables that are defined inside subprograms.
subprograms type check parameters
9.5 Parameter passing methods
9.5.1 Pass by value
- creates a deep copy of the object passed in from the caller, not a reference to the original object.
- if the deep copy gets changed with the subprogram, the callers object will not be changed.
9.5.2 Pass-by-Result
Pass-by-result is an implementation model for out mode parameters.
- helps assigning new values to multiple value-types.
ie. void Fixer(out int x, out int y)
9.5.3 Pass-by-Value-Result
- a combination of pass-by-value and pass-by-result
ie. void Fixer(int x, out int y)
9.5.4 Pass-by-Reference
- passes in an memory address of the object (shallow copy) , to the subprogram
- if the object is modified within the subprogram, the callers object will persist those changes.
9.7 Overloaded Subprograms
An overloaded subprogram is a subprogram that has the same name as another subprogram in the same referencing environment. Every version of an overloaded subprogram must have a unique protocol, that is, it must be different from the others in the number, order, or types of parameters or in return type.
9.8 Generic Subprograms (Generic Method)
-Software reuse can be an important contribute to software productivity.
-One way to re-use, is to lessen the need to create different subprograms to do the same thing for different data-types
- A polymorphic subprogram takes parameters of different type on different activations.
- Parametric polymorphism - is provided by a subprogram hat takes generic parameters that are used in type expressions that describe the types of the parameters of the subprogram.
i.e of a generic method
. public static T doit<t> (t pl)
Showing posts with label Concepts of programming languages. Show all posts
Showing posts with label Concepts of programming languages. Show all posts
Monday, 20 April 2015
11.0 - OOP Principles
*Inheritance
the ability to create class/interface which inherits certain aspects from inherited parent*Polymorphism
The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'.
Polymorphism can be static or dynamic. In static polymorphism, the response to a function is determined at the compile time. In dynamic polymorphism, it is decided at run-time.
Static Polymorphism
The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. They are:- Function overloading
- Operator overloading
Dynamic Polymorphism
-
C# allows you to create abstract classes that are used to provide
partial class implementation of an interface. Implementation is
completed when a derived class inherits from it. Abstract classes
contain abstract methods, which are implemented by the derived class.
The derived classes have more specialized functionality.
Here are the rules about abstract classes:
- You cannot create an instance of an abstract class
- You cannot declare an abstract method outside an abstract class
- When a class is declared sealed, it cannot be inherited,
- Abstract classes cannot be declared sealed.
* Encapsulation
Encapsulation,
in the context of C#, refers to an object's ability to hide data and
behavior that are not necessary to its user. Encapsulation enables a
group of properties, methods and other members to be considered a single
unit or object.
The following are the benefits of encapsulation:
Encapsulation is also known as information hiding.
The following are the benefits of encapsulation:
- Protection of data from accidental corruption
- Specification of the accessibility of each of the members of a class to the code outside the class
- Flexibility and extensibility of the code and reduction in complexity
- Lower coupling between objects and hence improvement in code maintainability
Encapsulation is also known as information hiding.
Uses access modifiers
Encapsulation,
in the context of C#, refers to an object's ability to hide data and
behavior that are not necessary to its user. Encapsulation enables a
group of properties, methods and other members to be considered a single
unit or object.
* Abstraction
Abstraction from Object Oriented Programming perspective is
extracting the core features of an object, without being
specific about the implementation details.helps reduce the complexity of the software
Sunday, 5 April 2015
8.0 Control Statements & structures.
Intro
Control statements
-Satements that allow for alternative control flow paths and others causing the repeated execution of sequences of statements.
- allow programs to be flexible and powerful
Control Stucture
- Is a control statement and the collection of statements whose execution it controls.
8.2 Selection Statements
- A selection statement provides the means of choice between two or more execution paths in a program.
8.2.1 Two Way Selection Statements
If control_expression
then clause
else clause
*note the expression immediately after the if keyword is called a control expression
Nested selectors - are just selection statements in selection statements. an if statement within an if statement
8.2.2 Multiple- Selection Statements
- Allow the selection of one or any number of statements.
- C+= java not C# - allow execution of more then one segment
var a = 9
switch (a)
case 9
a = a + 3 ' now eqauls 12
case 11
break
case 12 <---while hit here too
break
C# with statements different from c-base processors as they disallows implicit execution of more than one segment. each segment has to end with a break statement.
8.2 Iterative Statements
An iterative statement is one that causes a statement or collection of statement to be executed zero, one or more times. often called a loop.
ie. for statement, foreach statement, while statement
Control statements
-Satements that allow for alternative control flow paths and others causing the repeated execution of sequences of statements.
- allow programs to be flexible and powerful
Control Stucture
- Is a control statement and the collection of statements whose execution it controls.
8.2 Selection Statements
- A selection statement provides the means of choice between two or more execution paths in a program.
- two-way/n-way category i.e (2 -way) if then else, (n-way) if then if then, else
- multiple-way selectors (multiple selection) C++, java not so much C#
8.2.1 Two Way Selection Statements
If control_expression
then clause
else clause
*note the expression immediately after the if keyword is called a control expression
Nested selectors - are just selection statements in selection statements. an if statement within an if statement
8.2.2 Multiple- Selection Statements
- Allow the selection of one or any number of statements.
- C+= java not C# - allow execution of more then one segment
var a = 9
switch (a)
case 9
a = a + 3 ' now eqauls 12
case 11
break
case 12 <---while hit here too
break
C# with statements different from c-base processors as they disallows implicit execution of more than one segment. each segment has to end with a break statement.
8.2 Iterative Statements
An iterative statement is one that causes a statement or collection of statement to be executed zero, one or more times. often called a loop.
ie. for statement, foreach statement, while statement
Saturday, 4 April 2015
7.0 Expressions and Assignment Statements
Expressions are the fundamental means of specifying computations in a programming language.
The purpose of an assignment statement is to change the value of a variable.
In programming languages, arithmetic expressions consist of operators operands, parentheses and function calls.
An operator can be
Unary - meaning it has a single operand. ie: ! or ++ , ex: int c = x++
Binary - meaning it has two operands. ie: == ex: bool b = (c == d)
Ternary = Meaning it has three operands. ie: ?: ex: (input > 0) ? "yes" : "no"
Unaray addition is called the identity operator because it usually has no associated operation and thus has no effect on its operand.
var a = 10
(-a).Dump();
output = -10
yet variable a value still equals 10
7.2 Arithmetic Expressions
The purpose of an arithmetic expression is to specificity and arithmetic computation.
An implementation of such a computation must cause two actions . fetching the operands, usually from memory and executing the arithmetic operations on those operands.
7.2.1 Operator Evaluation Order
7.2.1.1 Precedence
- The order of evaluation of operators in the expression
- i.e. a + b * c
- The operator precedence rules for expression evaluation define the order in which the operator of difference precedence levels are evaluated. These are based on the hierarchy of operators priorities, as seen by the language designer.
7.2.1.2 Associativity
When an expression contains two adjacent occurrences of operators with the same level of precedence, the question of which operator is evaluated first. This is answered by the associativity rules of the language.
i.e. a - b + c
An operator can have either left to right associativity or right to left associativity
7.2.1.3 Parentheses
Programmers can alter the precedence and associativity rules by placing parentheses in expressions. A parenthesized part of an expression has precedence over its adjacent un-parenthesized parts. for example, although multiplication has precedence over addition, in the expression below, addition will be evaluated first.
i.e (A + B) * C
7.2.1.5 Conditional Expressions
We now look at the ternary operator ?: This operator is used to form conditional expressions.
Sometimes if-then-else statements are used to perform conditional expression assignment.
If (count == 0) Then {average = 0} Else {average = sum/ count)
average = (count == 0) ? 0 : sum/count
7.3 Overloaded Operators
The multiple use of an operator is called operator overloading and is generally thought to be acceptable, as long as readability and/or reliability don't suffer.
Using the same symbol for two completely unrelated operations is detrimental to readability.
Risks are that a programmer could overload * to be an addition operator.
7.4 Type Conversions
-Type conversions are either narrowing or widening.
- A narrowing conversion converts a value to a type that cannot store even approximations of all of the values of the original type. double to an int, Narrowing conversion are not always safe, sometimes the magnitude of the converted value is changed in the process.
- A widening conversion converts a value to a type that can include at least approximations of all of the value of the original type. ie. int to a double, Widening conversion are nearly always safe, meaning that the magnitude of the converted value is maintained.
7.4.1 Coercion in Expressions
- Implicit type conversion that is initiated by the compiler when an operator has two operands of a different type. With in the arithmetic expression example below the compiler would simply insert code to coerce the value of the int operand to a double
int a = 10
double b = 5.5
var c = a * b
Languages like java that don't allow such mixed mode expressions would just throw up a type error, and the programmer would have to do the conversion explicitly.
7.4.2 Explicit Type Conversion
Most languages provide some capability for doing explicit conversions, with widening and narrowing. In some cases warning messages are produced when an explicit narrowing conversion results in a significant change to the value of the object being converted.
In c-based languages, explicit type casts are called casts.
(double) sum
7.5 Relational and Boolean Expressions
7.5.1 Relational Expressions
- A relational operator is an operator that compares the values of it operands. ie. ==, !=
- A relational expression has two operands and one relational operator.
- The result value of a relational expression is Boolean.
-checks the a type of relationship between operands
below are example of relational operators
==, !=, >, <, >=, <=
7.5.2 Boolean Expressions
- Boolean expressions consist of Boolean variables, Boolean constants, relational expressions and Boolean operator. The operator usual includes those for AND OR and NOT operations.
var a = (a.value == 10 && b.value == 10 )
7.6 Short-Circuit Evaluation
A short-circuit evaluation of an expression is one in which the result is determined with evaluating all of the operands and/or operators. in the expression below
If (a >= 0) && (b<110)
If the variable a evaluation fails to find that variable a is greater then or equal to 0 then we already know that we don't need to evaluate the second relational expression to know that this whole Boolean expression results is false.
7.7 Assignment Statement
-Provides the mechanism by which the user can dynamically change the binding of values to variables.
- <target_variable><assignment_operator><expression>
7.7.2 Conditional targets
In C++
flag ? count 1 : count 2 = 0
equal to
if (flag) count1 = 0 else count 2 = 0
7.7.3 Compound Assignment Operators
- A compound assignment operator is a shorthand method of specifying a commonly needed form of assignment.
ie. sum += value is equivalent to sum = sum + value
7.7.4 Unary Assignment Operators
- operators with a single operand
- abbreviated assignments
example: sum = count++;
7.7.5 Assignment as an Expression
- an assignment expression within a relational expressions
IF ((c = a * b) ==100)
The purpose of an assignment statement is to change the value of a variable.
In programming languages, arithmetic expressions consist of operators operands, parentheses and function calls.
An operator can be
Unary - meaning it has a single operand. ie: ! or ++ , ex: int c = x++
Binary - meaning it has two operands. ie: == ex: bool b = (c == d)
Ternary = Meaning it has three operands. ie: ?: ex: (input > 0) ? "yes" : "no"
Unaray addition is called the identity operator because it usually has no associated operation and thus has no effect on its operand.
var a = 10
(-a).Dump();
output = -10
yet variable a value still equals 10
7.2 Arithmetic Expressions
The purpose of an arithmetic expression is to specificity and arithmetic computation.
An implementation of such a computation must cause two actions . fetching the operands, usually from memory and executing the arithmetic operations on those operands.
7.2.1 Operator Evaluation Order
7.2.1.1 Precedence
- The order of evaluation of operators in the expression
- i.e. a + b * c
- The operator precedence rules for expression evaluation define the order in which the operator of difference precedence levels are evaluated. These are based on the hierarchy of operators priorities, as seen by the language designer.
7.2.1.2 Associativity
When an expression contains two adjacent occurrences of operators with the same level of precedence, the question of which operator is evaluated first. This is answered by the associativity rules of the language.
i.e. a - b + c
An operator can have either left to right associativity or right to left associativity
7.2.1.3 Parentheses
Programmers can alter the precedence and associativity rules by placing parentheses in expressions. A parenthesized part of an expression has precedence over its adjacent un-parenthesized parts. for example, although multiplication has precedence over addition, in the expression below, addition will be evaluated first.
i.e (A + B) * C
7.2.1.5 Conditional Expressions
We now look at the ternary operator ?: This operator is used to form conditional expressions.
Sometimes if-then-else statements are used to perform conditional expression assignment.
If (count == 0) Then {average = 0} Else {average = sum/ count)
average = (count == 0) ? 0 : sum/count
7.3 Overloaded Operators
The multiple use of an operator is called operator overloading and is generally thought to be acceptable, as long as readability and/or reliability don't suffer.
Using the same symbol for two completely unrelated operations is detrimental to readability.
Risks are that a programmer could overload * to be an addition operator.
7.4 Type Conversions
-Type conversions are either narrowing or widening.
- A narrowing conversion converts a value to a type that cannot store even approximations of all of the values of the original type. double to an int, Narrowing conversion are not always safe, sometimes the magnitude of the converted value is changed in the process.
- A widening conversion converts a value to a type that can include at least approximations of all of the value of the original type. ie. int to a double, Widening conversion are nearly always safe, meaning that the magnitude of the converted value is maintained.
7.4.1 Coercion in Expressions
- Implicit type conversion that is initiated by the compiler when an operator has two operands of a different type. With in the arithmetic expression example below the compiler would simply insert code to coerce the value of the int operand to a double
int a = 10
double b = 5.5
var c = a * b
Languages like java that don't allow such mixed mode expressions would just throw up a type error, and the programmer would have to do the conversion explicitly.
7.4.2 Explicit Type Conversion
Most languages provide some capability for doing explicit conversions, with widening and narrowing. In some cases warning messages are produced when an explicit narrowing conversion results in a significant change to the value of the object being converted.
In c-based languages, explicit type casts are called casts.
(double) sum
7.5 Relational and Boolean Expressions
7.5.1 Relational Expressions
- A relational operator is an operator that compares the values of it operands. ie. ==, !=
- A relational expression has two operands and one relational operator.
- The result value of a relational expression is Boolean.
-checks the a type of relationship between operands
below are example of relational operators
==, !=, >, <, >=, <=
7.5.2 Boolean Expressions
- Boolean expressions consist of Boolean variables, Boolean constants, relational expressions and Boolean operator. The operator usual includes those for AND OR and NOT operations.
var a = (a.value == 10 && b.value == 10 )
7.6 Short-Circuit Evaluation
A short-circuit evaluation of an expression is one in which the result is determined with evaluating all of the operands and/or operators. in the expression below
If (a >= 0) && (b<110)
If the variable a evaluation fails to find that variable a is greater then or equal to 0 then we already know that we don't need to evaluate the second relational expression to know that this whole Boolean expression results is false.
7.7 Assignment Statement
-Provides the mechanism by which the user can dynamically change the binding of values to variables.
- <target_variable><assignment_operator><expression>
7.7.2 Conditional targets
In C++
flag ? count 1 : count 2 = 0
equal to
if (flag) count1 = 0 else count 2 = 0
7.7.3 Compound Assignment Operators
- A compound assignment operator is a shorthand method of specifying a commonly needed form of assignment.
ie. sum += value is equivalent to sum = sum + value
7.7.4 Unary Assignment Operators
- operators with a single operand
- abbreviated assignments
example: sum = count++;
7.7.5 Assignment as an Expression
- an assignment expression within a relational expressions
IF ((c = a * b) ==100)
Thursday, 19 March 2015
6.0 Data Types
6.1 Introduction
These are data types that are not defined in terms of other types.
6.2.1 Numeric Types
6.2.1.1 Integer
The most common primitive numeric data type is integer.
Many programming languages support different sizes of integers: byte, short, int and long.
Some languages like C++ and C#, include unsigned integer types.
Unsigned types are usually used for binary data.
A signed integer value is represented in a computer by a string of bits with one of the bits (typically the left most) representing the sign.
unsigned int 00000001 = 1
11111111 = 255
Signed int 00000000 = 0
00000001 = 1
01111111 = 127
10000000 = -128
11111111 = -1
6.2.1.2 Floating Points
Floating point data type model real numbers, but the representations are only approximations of most real values.
Most languages include two floating point types, often called float and double.
Float - 4 bytes
The double type is provided for situations where larger fractional parts are need. double the size of a float with 8 bytes.
6.2.1.4 Decimal
Decimal data types store a fixed number of decimal digits with the decimal point at a fixed position in the value.
- Date type for business data processing
-Have an advantage of being able to precisely store decimal values, at least those within a restricted range, which cannot be done with floating points.
- its takes at least four bit to code a decimal digit.
6.2.2 Boolean Types
Boolean types are perhaps the simplest of all types.
- Their range of values has two elements - true and false
- Any non-zero value is true
- Zero is false
- A Boolean value could be represent 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.
6.2.3 Character Types
Character data are store in computers as numeric coding.
-ASCII (American Standard code for information interchange) is the traditional character set.
- ASCII uses the value 0 to 127 to code 128 different characters.
-Because of globalization of business and the need for computers to communicate with computers around the world, the ASCII character set is becoming inadequate.
- Unicode has been developed as an alternative.
- 16 bit character set
-Includes characters from most of the worlds natural languages. ie, Thai digit, Cyrillic alphabet
- the first 128 characters are identical to ascii
- Used in C#
6.3 Character String Types
A character string type is one in which the values consist of sequences of characters.
The common string operations are assignment, catenation, sub-string reference, comparison and pattern matching.
6.4 User-definer ordinal types
- An ordinal type is one in which the range of possible values can be easily associated with the set of positive integers.
6.4.1 Enumeration Type
An enumeration type is one in which all of the possible values, which are name constants are provided, or enumerated in the definition.
- Away of defining and grouping collections of name constants. (enumeration constants)
- Sub range is a sub group in an enumeration type ie. Ratings 8,9,10 = high
6.5 Array Types
An array is a homogeneous aggregate of data elements in which an individual element is identified by its position in the aggregate, relative to the first element.
6.5.4 Heterogeneous Arrays - are arrays in which elements need not be the same type.
6.5.6 Array Operations - assignment, catenation, comparison for equality and inequality and slices.
6.5.7 Rectangular Array
- A rectangular array is a multidimensional array in which all of the rows have the same number of elements, all of the columns have the same number of elements
Jagged Array
- A jagged array is one in which the lengths of the rows need not be the same.
- i.e one row with 7 elements ,another row with 6, another row with 4
6.5.8 Slices
- A slice of an array is some substructure of that array.
6.9.6 Pointer
A pointer type is one in which the variable have a range of values that consist of memory address and a special value nil.
-The value nil is not a valid address and is used to indicate that pointer cannot currently be used to reference a memory cell
Pointer have two distinct purposes
1. Pointers provide some of the power of indirect addressing which is heavily used in assembly language programming.
2. Pointers provide a way to manage dynamic storage, A pointer can be used to access a location in the area where storage is dynamically allocated, which is usually called the heap.
Pointer Operations - assigning and de-referencing
Dangling pointer - A dangling pointer / reference, is a pointer that contains the address of a heap dynamic variable that has been de-allocated.
6.9.7 Reference Type
A reference type variable is similar to a pointer, with one important and fundamental difference.
A pointer refers to an address in memory, while a reference refers to an object or value in memory.
- A Data type defines a collection of data values and a set of predefined operations on those values.
- An important factor of determining the ease with which they can perform this task is how well the data types are available in the language being used match the objects in the real world.
- The two most common (non-scalar) data types are arrays and records. although the popularity of associate arrays has increased significantly.
- It is convenient, both logically and concretely, to think of variables as descriptors.
- A descriptor is the collection of attributes of a variable.
- If the attributes are all static, descriptors are required only at compile time.
- For dynamic attributes however they are used at run-time
- In all cases, descriptors are used for type checking and to build the code for the allocation and de-allocation operations
These are data types that are not defined in terms of other types.
6.2.1 Numeric Types
6.2.1.1 Integer
The most common primitive numeric data type is integer.
Many programming languages support different sizes of integers: byte, short, int and long.
Some languages like C++ and C#, include unsigned integer types.
Unsigned types are usually used for binary data.
A signed integer value is represented in a computer by a string of bits with one of the bits (typically the left most) representing the sign.
unsigned int 00000001 = 1
11111111 = 255
Signed int 00000000 = 0
00000001 = 1
01111111 = 127
10000000 = -128
11111111 = -1
6.2.1.2 Floating Points
Floating point data type model real numbers, but the representations are only approximations of most real values.
Most languages include two floating point types, often called float and double.
Float - 4 bytes
The double type is provided for situations where larger fractional parts are need. double the size of a float with 8 bytes.
6.2.1.4 Decimal
Decimal data types store a fixed number of decimal digits with the decimal point at a fixed position in the value.
- Date type for business data processing
-Have an advantage of being able to precisely store decimal values, at least those within a restricted range, which cannot be done with floating points.
- its takes at least four bit to code a decimal digit.
6.2.2 Boolean Types
Boolean types are perhaps the simplest of all types.
- Their range of values has two elements - true and false
- Any non-zero value is true
- Zero is false
- A Boolean value could be represent 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.
6.2.3 Character Types
Character data are store in computers as numeric coding.
-ASCII (American Standard code for information interchange) is the traditional character set.
- ASCII uses the value 0 to 127 to code 128 different characters.
-Because of globalization of business and the need for computers to communicate with computers around the world, the ASCII character set is becoming inadequate.
- Unicode has been developed as an alternative.
- 16 bit character set
-Includes characters from most of the worlds natural languages. ie, Thai digit, Cyrillic alphabet
- the first 128 characters are identical to ascii
- Used in C#
6.3 Character String Types
A character string type is one in which the values consist of sequences of characters.
The common string operations are assignment, catenation, sub-string reference, comparison and pattern matching.
6.4 User-definer ordinal types
- An ordinal type is one in which the range of possible values can be easily associated with the set of positive integers.
6.4.1 Enumeration Type
An enumeration type is one in which all of the possible values, which are name constants are provided, or enumerated in the definition.
- Away of defining and grouping collections of name constants. (enumeration constants)
- Sub range is a sub group in an enumeration type ie. Ratings 8,9,10 = high
6.5 Array Types
An array is a homogeneous aggregate of data elements in which an individual element is identified by its position in the aggregate, relative to the first element.
6.5.4 Heterogeneous Arrays - are arrays in which elements need not be the same type.
6.5.6 Array Operations - assignment, catenation, comparison for equality and inequality and slices.
6.5.7 Rectangular Array
- A rectangular array is a multidimensional array in which all of the rows have the same number of elements, all of the columns have the same number of elements
Jagged Array
- A jagged array is one in which the lengths of the rows need not be the same.
- i.e one row with 7 elements ,another row with 6, another row with 4
6.5.8 Slices
- A slice of an array is some substructure of that array.
6.9.6 Pointer
A pointer type is one in which the variable have a range of values that consist of memory address and a special value nil.
-The value nil is not a valid address and is used to indicate that pointer cannot currently be used to reference a memory cell
Pointer have two distinct purposes
1. Pointers provide some of the power of indirect addressing which is heavily used in assembly language programming.
2. Pointers provide a way to manage dynamic storage, A pointer can be used to access a location in the area where storage is dynamically allocated, which is usually called the heap.
Pointer Operations - assigning and de-referencing
Dangling pointer - A dangling pointer / reference, is a pointer that contains the address of a heap dynamic variable that has been de-allocated.
6.9.7 Reference Type
A reference type variable is similar to a pointer, with one important and fundamental difference.
A pointer refers to an address in memory, while a reference refers to an object or value in memory.
Wednesday, 4 March 2015
5.0 - QA
1. What are the design issues for names?
= The design issues for names are “Are the names case sensitive?” or “Are words for reserved words or keywords?”
2. What is the potential danger of case-sensitive names?
= readability (names that look alike, but are different).
3. In what way are reserved words better than keywords?
A reserved word is a special word that cannot be used as a user-defined name.
A keyword is a word that is special only in certain contexts.
4. What is an alias?
= When more than one variable can be used to access the same memory location, the variables are called aliases.
5. Which category of C++ reference variables is always aliases?
= Union types. Union is a type whose variables may store different type values at different times during program execution.
6. What is the l-values of a variables? What is the r-values?
= The l-values of a variable is its address. The r-values of a variable is its value.
7. Define binding and binding time.
= A binding is an association, such as between an attribute and an entity, or between an operation and a symbol. Binding time is the time at which binding takes place.
8. After language design and implementation [what are the four times bindings can take place in a program?]
9. Define static binding and dynamic binding.
= Static binding first occurs before run time and remains unchanged throughout program execution. dynamic binding first occurs during execution and can change during execution of the program.
10. What are the advantages and disadvantages of implicit declarations?
= The advantage is write-ability.
11. What are the advantages and disadvantages of dynamic type binding?
= The advantage is flexibility (generic program units).
12. Define static, stack-dynamic, explicit heap-dynamic, and implicit heap-dynamic variables. What are their advantages and disadvantages?
= Static: bound to memory cells before execution begins and remains bound to the same memory cell throughout the execution.
Stack-dynamic: storage bindings are created for variables when their declaration statements are elaborated.
Explicit heap-dynamic: allocated and deallocated by explicit directives, specified by the programmer, which take effect during execution.
Implicit heap-dynamic variables: Allocation and deallocation caused by assignment statements.
13. Define lifetime, scope, static scope, and dynamic scope.
= Lifetime: A time during which the variable is bound to a specific memory location. The lifetime begins when it is bound to a specific cell and ends when it is unbound from that cell.
Scope: The range of statements in which the variable is visible. A variable is visible in a statement if it can be referenced in that statement.
Static scope: is based on program text and to connect a name reference to a variable , you (or the compiler) must find the declaration.
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.
14. How is a reference to a non-local variable in a static-scoped program connected to its definition?
= A reference to a non-local variable in a static-scoped language with nested subprograms requires a two step access process:
1. Find the correct activation record instance
2. Determine the correct offset within that activation record instance
15. What is the general problem with static scoping?
= Usually too much access. Scope structure destroyed as program evolves.
16. What is the referencing environment of a statement?
= Set of all names visible to the statement.
17. What is a static ancestor of a subprogram? What is a dynamic ancestor of a subprogram?
= The static ancestors of a subprogram sub() are all the procedures in the program within which the procedure sub() is defined, i.e., the definition of the procedure sub() is nested. The definition of a procedure may be directly nested within only one procedure, called its static parent procedure. However, this static parent procedure may itself be nested within another procedure, and so on up to the main() program. All these procedures are considered to be static ancestors of the procedure sub(). Simply put, the static ancestors are those that strictly contain the subprogram in question.
The dynamic ancestors of a subprogram sub() are all the procedures called before sub() during the execution of a program, that have not yet finished executing. These are the procedures that are waiting for procedure sub() to finish executing before they can terminate. Simply put, dynamic ancestors are those that are called to reach the subprogram in question.
18. What is a block?
= The storage a variable is allocated when the section is entered and deallocated when the section is exited.
19. What is the purpose of the let constructs in functional languages?
= “let” introduces a new variable scope, and allows you to bind variables to values for that scope. It is often read as “let x be [value] in …”
22. What are the advantages and disadvantages of dynamic scoping?
= Advantage: convenience.
Disadvantage: cant type-check at compile time. Poor readability (can’t determine type of a variable statically).
23. What are the advantages of named constants?
= The advantages are readability and modifiability.
= The design issues for names are “Are the names case sensitive?” or “Are words for reserved words or keywords?”
2. What is the potential danger of case-sensitive names?
= readability (names that look alike, but are different).
3. In what way are reserved words better than keywords?
A reserved word is a special word that cannot be used as a user-defined name.
A keyword is a word that is special only in certain contexts.
4. What is an alias?
= When more than one variable can be used to access the same memory location, the variables are called aliases.
5. Which category of C++ reference variables is always aliases?
= Union types. Union is a type whose variables may store different type values at different times during program execution.
6. What is the l-values of a variables? What is the r-values?
= The l-values of a variable is its address. The r-values of a variable is its value.
7. Define binding and binding time.
= A binding is an association, such as between an attribute and an entity, or between an operation and a symbol. Binding time is the time at which binding takes place.
8. After language design and implementation [what are the four times bindings can take place in a program?]
- Language design time — bind operator symbols to operations
- Language implementation time– bind floating point type to a representation
- Compile time — bind a variable to a type in C or Java
- Load time — bind a C or C++ static variable to a memory cell)
- Runtime — bind a non-static local variable to a memory cell
9. Define static binding and dynamic binding.
= Static binding first occurs before run time and remains unchanged throughout program execution. dynamic binding first occurs during execution and can change during execution of the program.
10. What are the advantages and disadvantages of implicit declarations?
= The advantage is write-ability.
11. What are the advantages and disadvantages of dynamic type binding?
= The advantage is flexibility (generic program units).
12. Define static, stack-dynamic, explicit heap-dynamic, and implicit heap-dynamic variables. What are their advantages and disadvantages?
= Static: bound to memory cells before execution begins and remains bound to the same memory cell throughout the execution.
Stack-dynamic: storage bindings are created for variables when their declaration statements are elaborated.
Explicit heap-dynamic: allocated and deallocated by explicit directives, specified by the programmer, which take effect during execution.
Implicit heap-dynamic variables: Allocation and deallocation caused by assignment statements.
13. Define lifetime, scope, static scope, and dynamic scope.
= Lifetime: A time during which the variable is bound to a specific memory location. The lifetime begins when it is bound to a specific cell and ends when it is unbound from that cell.
Scope: The range of statements in which the variable is visible. A variable is visible in a statement if it can be referenced in that statement.
Static scope: is based on program text and to connect a name reference to a variable , you (or the compiler) must find the declaration.
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.
14. How is a reference to a non-local variable in a static-scoped program connected to its definition?
= A reference to a non-local variable in a static-scoped language with nested subprograms requires a two step access process:
1. Find the correct activation record instance
2. Determine the correct offset within that activation record instance
15. What is the general problem with static scoping?
= Usually too much access. Scope structure destroyed as program evolves.
16. What is the referencing environment of a statement?
= Set of all names visible to the statement.
17. What is a static ancestor of a subprogram? What is a dynamic ancestor of a subprogram?
= The static ancestors of a subprogram sub() are all the procedures in the program within which the procedure sub() is defined, i.e., the definition of the procedure sub() is nested. The definition of a procedure may be directly nested within only one procedure, called its static parent procedure. However, this static parent procedure may itself be nested within another procedure, and so on up to the main() program. All these procedures are considered to be static ancestors of the procedure sub(). Simply put, the static ancestors are those that strictly contain the subprogram in question.
The dynamic ancestors of a subprogram sub() are all the procedures called before sub() during the execution of a program, that have not yet finished executing. These are the procedures that are waiting for procedure sub() to finish executing before they can terminate. Simply put, dynamic ancestors are those that are called to reach the subprogram in question.
18. What is a block?
= The storage a variable is allocated when the section is entered and deallocated when the section is exited.
19. What is the purpose of the let constructs in functional languages?
= “let” introduces a new variable scope, and allows you to bind variables to values for that scope. It is often read as “let x be [value] in …”
22. What are the advantages and disadvantages of dynamic scoping?
= Advantage: convenience.
Disadvantage: cant type-check at compile time. Poor readability (can’t determine type of a variable statically).
23. What are the advantages of named constants?
= The advantages are readability and modifiability.
3.0 - QA
1. Define syntax and semantics!
= Syntax is the form of expressions, statements, and program units. Semantics is the description of those expressions, statements, and program units.
2. Who are language descriptions for?
= Language descriptions are for other language designers, implementers, and programmers (users of the language).
3. Define a left-recursive grammar rule.
= When a grammar rule has its LHS also appearing at the beginning of its RHS, the rule is said to be left-recursive. Left-recursive specifies left associativity. Unfortunately, left recursion disallows the use of some important syntax analysis algorithms. When such algorithms are to be used, the grammar must be modified to remove the left-recursion. This in turn, disallows the grammar from precisely specifying that certain operators are left associative. Fortunately, left associativity can be enforced by the compiler, even though the grammar does not dictate it.
7. What three extensions are common to most EBNFs?
= The first extension denotes an optional part of a RHS, which is delimited by brackets. For example:
<if_stmt> -> if ( <expr> ) stmt [ else <stmt> ]
The second extension is the use of braces in an RHS to indicate that the enclosed part can be repeated indefinitely or left out altogether. For example: <ident_list> -> ident {, <ident> }
The third extension deals with multiple choice options. For example: <term> -> <term> ( *|/|% ) <factor>
8. Distinguish between static and dynamic semantics.
= Static semantics is more on the legal forms of programs (syntax rather semantics) and is only indirectly related to the meaning of the programs during execution. Static semantics is named because the analysis required to check these specifications can be done at compile time. In many cases, the semantic rules of language state its type constraints.
Dynamic semantics is describing the meaning of the programs. Programmers need to know precisely what statements of a language do. Compile writers determine the semantics of a language for which they are writing compilers from English descriptions
10. What is the difference between a synthesized and an inherited attribute? = The synthesized attributes are the result of the attribute evaluation rules and may also use the values of the inherited attributes. The inherited attributes are passed down from parent nodes. In some approaches, synthesized attributes are used to pass semantic information up the parse tree, while inherited attributes help pass semantic information down it.
For instance, when constructing a language translation tool, such as a compiler, it may be used to assign semantic values to syntax constructions. Also, it is possible to validate semantic checks associated with a grammar, representing the rules of a language not explicitly imparted by the syntax.
12. What is the primary use of attribute grammars?
= An attribute grammar is a device used to describe more of the structure of a programming language than is possible with a context-free grammar. An attribute grammar is an extension to a context-free grammar. The primary purpose of an attribute grammar is it allows certain language rules to be described, such as type of compatibility. An attribute grammar is a formal way to define attributes for the productions of a formal grammar, associating these attributes to values. The evaluation occurs in the nodes of the abstract syntax tree, when the language is processed by some parser or compiler.
15. Describe the two levels of uses of operational semantics!
= There are different levels of uses of operational semantics. At the highest level, the interest is in the final result of the execution of a complete program. This is called natural operational semantics. At the lowest level, operational semantics can be used to determine the precise meaning of a program through an examination of the complete sequence of state changes that occur when the program is executed, This use is called structural operational semantics.
16. In denotational semantics, what are the syntactic and semantic domains?
= The mapping functions of a denotational semantics programming language specification, like all functions in mathematics, have a domain and a range.
the syntactic domain is called the domain because it is syntactic structures that are mapped. The domain is the collection of values that are legitimate parameters to the function; the range is the collections of objects to which the parameters are mapped.
the semantic domain is called the range.
19. What two things must be defined for each language entity in order to construct a denotational description of the language?
= objects and functions
20. Which part of an inference rule is the antecedent?
= The top part of an inference rule is called the antecedent.
21. When a grammar rule said to be left recursive?
= When a grammar rule has its LHS also appearing at the beginning of its RHS, the rule is said to be left-recursive. This left recursion specifies left associativity.
22. Give an example of an ambiguous grammar.
23. On what branch of mathematics is axiomatic semantics based?
= mathematics logic
25. What is the problem with using a software pure interpreter for operational semantics?
= The detailed characteristics of the particular computer would make actions difficult to understand. Such a semantic definition would be machine-dependent.
26. Explain what the preconditions and postconditions of a given statement mean in axiomatic semantics.
= An assertion before a statement (a precondition) states the relationships and constraints among variables that are true at that point in execution. An assertion following a statement is a postcondition.
27. What is loop invariant? Explain with an example.
= The corresponding step in the axiomatic semantics of a while loop is finding an assertion called a loop invariant, which is crucial to finding the weakest precondition. The loop invariant must satisfy a number of requirements to be useful. First, the weakest precondition for the while loop must guarantee the truth of the loop invariant. In turn, the loop invariant must guarantee the truth of the postcondition upon loop termination. These constraints move us from the inference rule to the axiomatic description. During execution of the loop-controlling Boolean expression and the loop body statements. Hence, the name invariant.
28. What is the use of the wp function? Why it is called a predicate transformer?
= A weakest precondition is the least restrictive precondition that will guarantee the postcondition. It is often called a predicate transformer because it takes a predicate, or assertion as a parameter and returns another predicate.
= Syntax is the form of expressions, statements, and program units. Semantics is the description of those expressions, statements, and program units.
2. Who are language descriptions for?
= Language descriptions are for other language designers, implementers, and programmers (users of the language).
3. Define a left-recursive grammar rule.
= When a grammar rule has its LHS also appearing at the beginning of its RHS, the rule is said to be left-recursive. Left-recursive specifies left associativity. Unfortunately, left recursion disallows the use of some important syntax analysis algorithms. When such algorithms are to be used, the grammar must be modified to remove the left-recursion. This in turn, disallows the grammar from precisely specifying that certain operators are left associative. Fortunately, left associativity can be enforced by the compiler, even though the grammar does not dictate it.
7. What three extensions are common to most EBNFs?
= The first extension denotes an optional part of a RHS, which is delimited by brackets. For example:
<if_stmt> -> if ( <expr> ) stmt [ else <stmt> ]
The second extension is the use of braces in an RHS to indicate that the enclosed part can be repeated indefinitely or left out altogether. For example: <ident_list> -> ident {, <ident> }
The third extension deals with multiple choice options. For example: <term> -> <term> ( *|/|% ) <factor>
8. Distinguish between static and dynamic semantics.
= Static semantics is more on the legal forms of programs (syntax rather semantics) and is only indirectly related to the meaning of the programs during execution. Static semantics is named because the analysis required to check these specifications can be done at compile time. In many cases, the semantic rules of language state its type constraints.
Dynamic semantics is describing the meaning of the programs. Programmers need to know precisely what statements of a language do. Compile writers determine the semantics of a language for which they are writing compilers from English descriptions
10. What is the difference between a synthesized and an inherited attribute? = The synthesized attributes are the result of the attribute evaluation rules and may also use the values of the inherited attributes. The inherited attributes are passed down from parent nodes. In some approaches, synthesized attributes are used to pass semantic information up the parse tree, while inherited attributes help pass semantic information down it.
For instance, when constructing a language translation tool, such as a compiler, it may be used to assign semantic values to syntax constructions. Also, it is possible to validate semantic checks associated with a grammar, representing the rules of a language not explicitly imparted by the syntax.
12. What is the primary use of attribute grammars?
= An attribute grammar is a device used to describe more of the structure of a programming language than is possible with a context-free grammar. An attribute grammar is an extension to a context-free grammar. The primary purpose of an attribute grammar is it allows certain language rules to be described, such as type of compatibility. An attribute grammar is a formal way to define attributes for the productions of a formal grammar, associating these attributes to values. The evaluation occurs in the nodes of the abstract syntax tree, when the language is processed by some parser or compiler.
15. Describe the two levels of uses of operational semantics!
= There are different levels of uses of operational semantics. At the highest level, the interest is in the final result of the execution of a complete program. This is called natural operational semantics. At the lowest level, operational semantics can be used to determine the precise meaning of a program through an examination of the complete sequence of state changes that occur when the program is executed, This use is called structural operational semantics.
16. In denotational semantics, what are the syntactic and semantic domains?
= The mapping functions of a denotational semantics programming language specification, like all functions in mathematics, have a domain and a range.
the syntactic domain is called the domain because it is syntactic structures that are mapped. The domain is the collection of values that are legitimate parameters to the function; the range is the collections of objects to which the parameters are mapped.
the semantic domain is called the range.
19. What two things must be defined for each language entity in order to construct a denotational description of the language?
= objects and functions
20. Which part of an inference rule is the antecedent?
= The top part of an inference rule is called the antecedent.
21. When a grammar rule said to be left recursive?
= When a grammar rule has its LHS also appearing at the beginning of its RHS, the rule is said to be left-recursive. This left recursion specifies left associativity.
22. Give an example of an ambiguous grammar.
= <program> →<stmts>
<stmts> → <stmt> | <stmt> ; <stmts>
<stmt> → <var> = <expr>
<var> → a | b | c | d
<expr> → <term> + <term> | <term> – <term>
<term> → <var> | const
= mathematics logic
25. What is the problem with using a software pure interpreter for operational semantics?
= The detailed characteristics of the particular computer would make actions difficult to understand. Such a semantic definition would be machine-dependent.
26. Explain what the preconditions and postconditions of a given statement mean in axiomatic semantics.
= An assertion before a statement (a precondition) states the relationships and constraints among variables that are true at that point in execution. An assertion following a statement is a postcondition.
27. What is loop invariant? Explain with an example.
= The corresponding step in the axiomatic semantics of a while loop is finding an assertion called a loop invariant, which is crucial to finding the weakest precondition. The loop invariant must satisfy a number of requirements to be useful. First, the weakest precondition for the while loop must guarantee the truth of the loop invariant. In turn, the loop invariant must guarantee the truth of the postcondition upon loop termination. These constraints move us from the inference rule to the axiomatic description. During execution of the loop-controlling Boolean expression and the loop body statements. Hence, the name invariant.
28. What is the use of the wp function? Why it is called a predicate transformer?
= A weakest precondition is the least restrictive precondition that will guarantee the postcondition. It is often called a predicate transformer because it takes a predicate, or assertion as a parameter and returns another predicate.
Sunday, 22 February 2015
5.0 Names, Binding, Type Checking and Scopes
1.0 Names (identifiers)
i.e in C# for, if , new, this
Contextual Keyword - A keyword that is special only in certain contexts, but it is not a reserved word in C#. Some contextual keywords, such as partial and where, have special meanings in two or more contexts.
i.e in C# - from, select. var , add, remove, value
There is one potential problem with reserved words; If the language includes a large number of reserved words, the user has the difficulty making up names that are not reserved. the best example is COBOL that has 300 reserved words compared to C# which has 79.
2.0 Variables
A program variable is an abstraction of a computer memory cell or collection of cells.
In some cases, the characteristics of these abstractions are very close to the characteristics of the memory cells; an example is an integer variable, which is usually represented directly in one of more bytes of memory.
In other cases, the abstractions are far removed for the organization of hardware memory, as with a three-dimensional array, which requires a software were mapping function to support abstraction.
A variable can be characterized as a sextuple of attributes: (name, address, value, type, lifetime, scope).
2.1 Name
Refer to Section 1.0
2.2 Address
The address of a variable is the machine memory address in which it is associated.
In many languages, it is possible for the same variable to be associated with different addresses at different times in the program. For example if a subprogram has a local variable that is allocated from the run time stack when the subprogram is called, different calls may result in that variable having different addresses.
Aliases - Multiple variables can point to the same memory address. When more than one variable can be used to access the same memory location they are called aliases. This hinders readability because it allows a variable to have its value changed by an assignment to a different variable.
references variables are aliases , Aliasing can be created in many languages through subprogram parameters.
2.3 Type
The type of a variable determines the range of values the variable can store and the set of operations that are defined for values of the type. For example, the int type in Java specified a values range of -2147483648 to 2147483647 and arithmetic operations of adding, subtraction, multiplication, division and modulus
2.4 Value
The value of a variable is the contents of the memory cell or cells associated with the variable.
It is convenient to think of computer memory in terms of abstract cells.
Physical cells (only 8 bits in length) are far to small for most program variables.
We define an abstract cell to have the size required by the variable with which it is associated
i.e Even though a floating point number could occupy 4 physical cells, we think of it as occupying one abstract memory cell.
3.0 Binding
Binding is an association, such as
Binding time - The time that the binding takes place is called the binding time.Binding can take place at
Static Binding - A binding is static if it first occurs before run time and remains unchanged throughout the program execution. When you define the type in declaration statement.
Advantage - Compiler can pick up errors sooner
Dynamic Binding (Javascript, PHP) -
If the binding first occurs during run time or can change in the course of program execution.The type of a variable is not specified by a declaration statement, nor can it be determined by the spelling of its name.
When the assignment statement is executed , the variable being assigned is bound to the type of the value of the expression on the right hand side of the assignment.
i.e in JavaScript, below would dynamically change the type of the variable names 'list'
list = [1.23, 123];
list = 54
4.0 Storage, Binding and Lifetime
Storage Bindings - binding a variable to be stored in a memory cell
Allocation - is the process of binding a variable to a memory cell from a pool of available memory.
De-allocation - is the process of placing a memory cell that has been unbound from a variable back into the pool of available memory.
Lifetime - The lifetime of a variable is the time during which the variable is bound to a specific memory locations. The lifetime of a variable begins when is bound to a specific cell and ends when it is unbound from that cell.
Heap - The heap is a collection of storage cells whose organization is highly disorganized because of the unpredictability of its use.
Run time Stack - The run time stack is data structure that stores information about the active sub-programs of a computer program. the last called is first to complete, hence the word common naming 'the stack'. it de-allocates the memory of the subprogram when then sub-program has completed its job.
- A variable will be stored on the run-time stack or the heap depending on whether the lifetime of the storage cannot be determined ahead of time.
4.1 Static Variables
- Bound to memory cells before program execution begins and remain bound to those same memory cells until program execution terminates.
- global access variables are static variables
4.2 Stack-Dynamic Variables
- Stack-Dynamic Variables are those whose storage bindings are created when their declaration statements are elaborated, but whose types are statically bound.
- for example, the variable declarations that appear at the beginning of a java method are elaborated when the method is called and the variable defined by those declarations are de-allocated when the method completes its execution.
4.3 Explicit Heap-Dynamic Variables
- Explicit heap-dynamic variables are nameless (abstract) memory cells that are allocated and de-allocated by explicit run time instructions specified by the programmers.
-These variables, which are allocated and de-allocated to the heap, can only be reference through pointer and reference variables.
4.4 Implicit Heap-Dynamic Variables
- Implicit Heap-Dynamic Variables are bound to heap storage only when they are assign values. in fact all their attributes are bound every time they are assign.
i.e in this an example in java-script when a variable dynamically goes from a string to an numeric array,
highs= "yolo"
highs= [34,56,98,21,79]
5.0 Type Checking
Type checking is the activity of ensuring that the operands of an operator are of compatable types.
Coercion - A compatible type is one that either is legal for the operator or is allowed under language to the implicitly converted by compiler generated code to a legal type. This is called coecion. Ie. Int + float , the int is coerced to a float.
Type Error - A type error is the application of an operator to an operand of an inappropriate type.
Static type checking - run at compile time (C#)
Dynamic type checking - run at run time (Javascript)
6.0 Strong Typing
7.0 Type Equivalence (compatibility)
-The compatibility rules dictate the types of operands that are acceptable for each of the operators and there by specify the possible type errors of the language.
The rules are called compatibility because in some cases the type of an operand can be implicitly converted by the compile or run-time system, to make it acceptable to the operator.
-Compatibility rules help with coercion.
i.e an int is type compatible with a float amongst a addition operator. int (operand - this will be coerced to a float) + (operator) float(operand)
8.0 Scope
- The scope of a variable is the range of statements in which the variable is visible. A variable is visible in a statement if it can referenced in that statement.
Local - A variable is local in a program untir or block if it is delcared there.
Non Local - A variable in non local of a program unit or block when the variable within the program unit or block, but are not declare there.
8.1 Static scoping
Static scoping is so named because the scope of a variable can be statically determined, that is, prior to execution. this permits a program reader to determine the type of every variable in a program.
9 Scope and life time
Scope and lifetime are unrelated - even though it may seem so .. i.e below The scope of the variable "sum" is completely contained within the compute function. it does not extend to the body of the function print header, although the print header function executes in the midst of execution of compute. Howe-ever the life time of "sum" extends over the time during which print header method executes. What ever storage location sum is bound to before the call to printheader, that binding will continue during and after the execution of printheader.
void compute()
{
int sum;
...
printHeader();
}
10 Referencing Environments
The referencing environment of a statement is the collection of all variables that are visible in the statement. The referencing environment of a statement in a static scope language is the variable declared in its local scope plus the collection of all variables of its ancestor scopes that are visible.
11. Named Constants
- A named constant is a viarable that is bound to a value once only;
- Name constant are usually to aid readability and program reliability,
- i.e const pi = 3.14159, would help readability instead of just using the number
C# has two kinds of names constants, those defined with
Const - are implicitly static, static bound to value cant be changed.
Read-only - Dynamically bound to values. value can define when the contain object is created.
- A name is a string of characters to identify some entity in a program
- Names are a fundamental attribute for variables
- Two design issues for names are:
- Are they case sensitive
- Are the special words of the language reserved words or keywords
- Names can have character length restrictions in languages (31 characters in FORTRAN)
- Can consist of letters, digits and Underscore, underscore now less popular with camel case
i.e in C# for, if , new, this
Contextual Keyword - A keyword that is special only in certain contexts, but it is not a reserved word in C#. Some contextual keywords, such as partial and where, have special meanings in two or more contexts.
i.e in C# - from, select. var , add, remove, value
There is one potential problem with reserved words; If the language includes a large number of reserved words, the user has the difficulty making up names that are not reserved. the best example is COBOL that has 300 reserved words compared to C# which has 79.
2.0 Variables
A program variable is an abstraction of a computer memory cell or collection of cells.
In some cases, the characteristics of these abstractions are very close to the characteristics of the memory cells; an example is an integer variable, which is usually represented directly in one of more bytes of memory.
In other cases, the abstractions are far removed for the organization of hardware memory, as with a three-dimensional array, which requires a software were mapping function to support abstraction.
A variable can be characterized as a sextuple of attributes: (name, address, value, type, lifetime, scope).
2.1 Name
Refer to Section 1.0
2.2 Address
The address of a variable is the machine memory address in which it is associated.
In many languages, it is possible for the same variable to be associated with different addresses at different times in the program. For example if a subprogram has a local variable that is allocated from the run time stack when the subprogram is called, different calls may result in that variable having different addresses.
Aliases - Multiple variables can point to the same memory address. When more than one variable can be used to access the same memory location they are called aliases. This hinders readability because it allows a variable to have its value changed by an assignment to a different variable.
references variables are aliases , Aliasing can be created in many languages through subprogram parameters.
2.3 Type
The type of a variable determines the range of values the variable can store and the set of operations that are defined for values of the type. For example, the int type in Java specified a values range of -2147483648 to 2147483647 and arithmetic operations of adding, subtraction, multiplication, division and modulus
2.4 Value
The value of a variable is the contents of the memory cell or cells associated with the variable.
It is convenient to think of computer memory in terms of abstract cells.
Physical cells (only 8 bits in length) are far to small for most program variables.
We define an abstract cell to have the size required by the variable with which it is associated
i.e Even though a floating point number could occupy 4 physical cells, we think of it as occupying one abstract memory cell.
3.0 Binding
Binding is an association, such as
- between an attribute and an entity,
- between an operation and a symbol
Binding time - The time that the binding takes place is called the binding time.Binding can take place at
- Language design time
- I.e The Astrix symbol (*) is usually bound to the multiplication operation of a language at language design time
- Language implementation time
- I.e A data-type such as int in c, is bound to a range of possible values at
Language implementation time
- I.e A data-type such as int in c, is bound to a range of possible values at
- Compile time
- I.e A variable in a java program may be bound to its a data-type at compile time
- Load time
- I.e A variable may be loaded to a storage cell when the program is loaded into memory, This binding in some cases does not happen until run-time
- I.e A variable may be loaded to a storage cell when the program is loaded into memory, This binding in some cases does not happen until run-time
- Link time
- I.e A call to a library subprogram is bound to the subprogram code at link time.
- Run time
- I.e A variable may be loaded to a storage cell at run time
Static Binding - A binding is static if it first occurs before run time and remains unchanged throughout the program execution. When you define the type in declaration statement.
Advantage - Compiler can pick up errors sooner
Dynamic Binding (Javascript, PHP) -
If the binding first occurs during run time or can change in the course of program execution.The type of a variable is not specified by a declaration statement, nor can it be determined by the spelling of its name.
When the assignment statement is executed , the variable being assigned is bound to the type of the value of the expression on the right hand side of the assignment.
i.e in JavaScript, below would dynamically change the type of the variable names 'list'
list = [1.23, 123];
list = 54
4.0 Storage, Binding and Lifetime
Storage Bindings - binding a variable to be stored in a memory cell
Allocation - is the process of binding a variable to a memory cell from a pool of available memory.
De-allocation - is the process of placing a memory cell that has been unbound from a variable back into the pool of available memory.
Lifetime - The lifetime of a variable is the time during which the variable is bound to a specific memory locations. The lifetime of a variable begins when is bound to a specific cell and ends when it is unbound from that cell.
Heap - The heap is a collection of storage cells whose organization is highly disorganized because of the unpredictability of its use.
Run time Stack - The run time stack is data structure that stores information about the active sub-programs of a computer program. the last called is first to complete, hence the word common naming 'the stack'. it de-allocates the memory of the subprogram when then sub-program has completed its job.
- A variable will be stored on the run-time stack or the heap depending on whether the lifetime of the storage cannot be determined ahead of time.
4.1 Static Variables
- Bound to memory cells before program execution begins and remain bound to those same memory cells until program execution terminates.
- global access variables are static variables
4.2 Stack-Dynamic Variables
- Stack-Dynamic Variables are those whose storage bindings are created when their declaration statements are elaborated, but whose types are statically bound.
- for example, the variable declarations that appear at the beginning of a java method are elaborated when the method is called and the variable defined by those declarations are de-allocated when the method completes its execution.
4.3 Explicit Heap-Dynamic Variables
- Explicit heap-dynamic variables are nameless (abstract) memory cells that are allocated and de-allocated by explicit run time instructions specified by the programmers.
-These variables, which are allocated and de-allocated to the heap, can only be reference through pointer and reference variables.
4.4 Implicit Heap-Dynamic Variables
- Implicit Heap-Dynamic Variables are bound to heap storage only when they are assign values. in fact all their attributes are bound every time they are assign.
i.e in this an example in java-script when a variable dynamically goes from a string to an numeric array,
highs= "yolo"
highs= [34,56,98,21,79]
5.0 Type Checking
Type checking is the activity of ensuring that the operands of an operator are of compatable types.
Coercion - A compatible type is one that either is legal for the operator or is allowed under language to the implicitly converted by compiler generated code to a legal type. This is called coecion. Ie. Int + float , the int is coerced to a float.
Type Error - A type error is the application of an operator to an operand of an inappropriate type.
Static type checking - run at compile time (C#)
Dynamic type checking - run at run time (Javascript)
6.0 Strong Typing
- A language is strong typed if type errors are always detected.
- This requires that the types of all operands can be determined. Either at compile time or run time.
- The importance of strong typing lies in its ability to detect all uses of variables that result in type errors.
- A strong typed language also allows the detection, at run time, of uses of the incorrect type values in variables that can store values off more then on type.
7.0 Type Equivalence (compatibility)
-The compatibility rules dictate the types of operands that are acceptable for each of the operators and there by specify the possible type errors of the language.
The rules are called compatibility because in some cases the type of an operand can be implicitly converted by the compile or run-time system, to make it acceptable to the operator.
-Compatibility rules help with coercion.
i.e an int is type compatible with a float amongst a addition operator. int (operand - this will be coerced to a float) + (operator) float(operand)
8.0 Scope
- The scope of a variable is the range of statements in which the variable is visible. A variable is visible in a statement if it can referenced in that statement.
Local - A variable is local in a program untir or block if it is delcared there.
Non Local - A variable in non local of a program unit or block when the variable within the program unit or block, but are not declare there.
8.1 Static scoping
Static scoping is so named because the scope of a variable can be statically determined, that is, prior to execution. this permits a program reader to determine the type of every variable in a program.
9 Scope and life time
Scope and lifetime are unrelated - even though it may seem so .. i.e below The scope of the variable "sum" is completely contained within the compute function. it does not extend to the body of the function print header, although the print header function executes in the midst of execution of compute. Howe-ever the life time of "sum" extends over the time during which print header method executes. What ever storage location sum is bound to before the call to printheader, that binding will continue during and after the execution of printheader.
void compute()
{
int sum;
...
printHeader();
}
10 Referencing Environments
The referencing environment of a statement is the collection of all variables that are visible in the statement. The referencing environment of a statement in a static scope language is the variable declared in its local scope plus the collection of all variables of its ancestor scopes that are visible.
11. Named Constants
- A named constant is a viarable that is bound to a value once only;
- Name constant are usually to aid readability and program reliability,
- i.e const pi = 3.14159, would help readability instead of just using the number
C# has two kinds of names constants, those defined with
Const - are implicitly static, static bound to value cant be changed.
Read-only - Dynamically bound to values. value can define when the contain object is created.
Saturday, 21 February 2015
3.0, Semantics and semantics
Semantics is the meaning of expressions, statements, and program
units. (i,e this is an if statement)
Syntax is the form of its expressions, statements, and program units. (ie. the if statement syntax is different in C# and Vb.net)
If(<boolean_expre> ) { Statement ; }
If (<boolean_expre> ) Then Statement End If
------------
index = 2 * count = 12
Lexeme - Small units that don't offer a description (A basic unit of meaning) (programming units)
Token = A category of lexemes
Lexemes Token
Index indentfier
= eqaul_sign
2 int_literal
* mult_op
Count identifier+ plus_op
17 int_literal
; semicolon or end_of_statement
---------
Backus naur form (BNF) is a metalanguage (language to describe a language) for programming languages
ie. a BNF description of a if and a if else statement would be
<if_stmt> -> if <logic_expr> then <stmt>
| if <logic_expr> then <stmt>else <stmt>
The <if_stmt> symbol on the left hand side (LHS) of the -> arrow, is the abstraction being defined.
The text to the right of the arrow (RHS) is the definition of the LHS. it consists of of some mixture of tokens lexemes and references to other abstractions.
Multiple definitions can be written as a single rule, with different definition separated by the | symbol
When describing lists for example a variable list of identifiers
It is common to use recursion
A rule is recursive if the LHS appears in its RHS
<indent_list> => identifier
| identifier, <indent_list>
--------
Operator Precedence
A = B + C * D
When an expression includes two different operations for example in the above * and +,
one obvious semantic issue is the order of evaluation of the two operators (is it add then multiply or is it visa versa in the above express. This semantic question can be answer by assignment different precedence levels to operators. If * is higher in precedence, then it will be the one used first.
Associativity of Operators
When an expression includes two operators that have the same precedence (as * and / usually do), a semantic rule is required to specify which should have precedence. The rule is named associativity.
A = A / B * C
Usually the correct order if left associative (the direction we read) so for this example in we would do the division first.
But it can also in times be right associative, to indicate right associativity right recursion can be used. (LSH right of the RHS) ie.
<factor> => <exp> ** <factor>
Parse Trees
Parsing is the problem of transforming a linear sequence of characters into a syntax tree
Read from left most bottom most


Syntax is the form of its expressions, statements, and program units. (ie. the if statement syntax is different in C# and Vb.net)
If(<boolean_expre> ) { Statement ; }
If (<boolean_expre> ) Then Statement End If
------------
index = 2 * count = 12
Lexeme - Small units that don't offer a description (A basic unit of meaning) (programming units)
Token = A category of lexemes
Lexemes Token
Index indentfier
= eqaul_sign
2 int_literal
* mult_op
Count identifier+ plus_op
17 int_literal
; semicolon or end_of_statement
---------
Backus naur form (BNF) is a metalanguage (language to describe a language) for programming languages
ie. a BNF description of a if and a if else statement would be
<if_stmt> -> if <logic_expr> then <stmt>
| if <logic_expr> then <stmt>else <stmt>
The <if_stmt> symbol on the left hand side (LHS) of the -> arrow, is the abstraction being defined.
The text to the right of the arrow (RHS) is the definition of the LHS. it consists of of some mixture of tokens lexemes and references to other abstractions.
Multiple definitions can be written as a single rule, with different definition separated by the | symbol
When describing lists for example a variable list of identifiers
It is common to use recursion
A rule is recursive if the LHS appears in its RHS
<indent_list> => identifier
| identifier, <indent_list>
--------
Operator Precedence
A = B + C * D
When an expression includes two different operations for example in the above * and +,
one obvious semantic issue is the order of evaluation of the two operators (is it add then multiply or is it visa versa in the above express. This semantic question can be answer by assignment different precedence levels to operators. If * is higher in precedence, then it will be the one used first.
Associativity of Operators
When an expression includes two operators that have the same precedence (as * and / usually do), a semantic rule is required to specify which should have precedence. The rule is named associativity.
A = A / B * C
Usually the correct order if left associative (the direction we read) so for this example in we would do the division first.
But it can also in times be right associative, to indicate right associativity right recursion can be used. (LSH right of the RHS) ie.
<factor> => <exp> ** <factor>
Parse Trees
Parsing is the problem of transforming a linear sequence of characters into a syntax tree
Read from left most bottom most
Wednesday, 21 January 2015
1.0 - Q/A
Q & A
1. Why is it useful for a programmer to have some background in language design, even though he or she may never actually design a programming language
Increased capacity to express ideas
Improved background for choosing appropriate languages.
Increased ability to learn new languages.
Better understanding of the significance of an implementation.
2. How can knowledge of programming language characteristics benefit the whole computing community?
If those who choose a language, are better informed, then perhaps better languages would eventually squeeze out poorer ones.
3. What programming language has dominated scientific computing over the past 45 years?
FORTRAN - FORTRAN has been used for a long time for scientific computing. It was the first language for scientific applications because FORTRAN provides efficiency which was the primary concern for scientific applications.
4. What programming language has dominated business applications over the past 45 years?
COBOL - COBOL was the first successful high-level language for business. It is the most commonly used language for business applications because business languages are characterized by facilities for producing elaborate reports, precise ways of describing, strong decimal numbers, character data and the ability to specify decimal arithmetic operations.
5. What programming language has dominated artificial intelligence over the past 45 years?
LISP - LISP which appeared in 1959.Artificial Intelligence (AI) is a broad area of computer applications characterized by the used of symbolic rather than numeric computations.
6. In what language was UNIX written?
The UNIX operating system is written almost entirely in C which has made it relatively easy to port, or move to different machines. Some of the characteristics of C make it a good choice for systems programming. It is low level, execution efficient and doesn’t burden the user with many safety restrictions.
7.What is the disadvantage of having to many features in a language?
If a language has to many features, some programmers wont be familiar with them all, leading to the misuse of some features and disuse of others.
8.How can user-defined operator overloading harm readability of a program?
If a programmer doesn't do it sensibly, it can reduce readability.
9. What is one example of lack of orthogonality in the design of C?
Consider the following rules and exceptions in C. Although C has two kinds of structured data-types arrays and records (structs). records can be any data type except void or a structure of the same type. An array element can be any data type except a void or a function. Parameters are passed by value, unless they are arrays, in which they are , in effect, passed by reference.
10. What language used orthogonality as a primary design criterion?
ALGOL 68 - ALGOL 68 is the most orthogonal programming language because every language constructs in ALGOL 68 has a type, and there are no restrictions on those types. But LISP can also be said as a good combination of simplicity and orthogonality. LISP a functional language is one in which computations are made primarily by applying a function to a given program.
11. What primitive control statement is used to build more complicated control statements in languages that lack them?
It is “goto”, but in the 1970s, the use of “goto” statements was replaced by structured programming, which could be read from top to bottom. (While, in newer languages)
12. What construct of a programming language provides process abstractions?
Programming languages usually contain abstractions for defining and manipulating data structures or controlling the flow of execution. The practical necessity that a programming language supports adequate abstractions is expressed by the abstraction principal. This principle is sometimes formulated as recommendation to the programmer to make proper use of such abstractions.
13.What does it mean for a program to be reliable?
A program is said to be reliable if it performs to its specifications under all conditions. Factors that affect reliability are type checking, exception handling, aliasing, readability and write-ability
14. Why is type checking the parameters of a subprogram important?
Type checking is important because run-time type checking is expensive, compile-time type checking is more desirable. Furthermore, the earlier errors in programs are detected, the less expensive it is to make the required repairs..
15. What is aliasing?
Aliasing is having two or more distinct names that can be used to access the same memory cell. It is now widely accepted that aliasing is a dangerous feature in a programming language. In some languages, aliasing is used to overcome deficiencies in the language’s data abstraction facilities.
16.What is exception handling?
Exception handling is the ability of a program to intercept run-time errors (as well as the unusual conditions detectable by the program), take corrective measures, and then continue in an obvious aid to reliability.
17. Why is reliability important to write-ability?
Readability is important to write-ability because if a programming language is difficult to read and understand then it can be difficult for a programmer to create new code that might need to interact or use other code. Often times code needs to be modified and if a program is difficult to read then it is difficult to add new code to it.
18.How is the cost of compilers for a given language related to the design of that language.
A language that requires many run-time type checks will prohibit fast code execution, regardless of the quality of the compiler.
19. What has been the strongest influence of programming language design over the past 50 years.
Most of the past 50 years have been designed around the prevalent computer architecture, called the von Neumann architecture, after one of its originators, John von Neumann.
20. What is the name of the category of programming languages whose structure is dedicated by the Von Neumann computer architecture?
These languages are called the imperative languages.
21 What two programming language deficiencies were discovered as a result of the research in software development in the 1970s.
The late 1960s and early 70s brought intense analysis of software development. the result in large begun the structure programming movement of both the software development process and program language design.
An important reason for this research was the shift in the major cost of computing from hardware to software. The primary programming language deficiencies that were discovered were in-completeness of type checking and inadequacy of control statements (requiring the extensive use of gotos).
22. What are the three fundamental features of Object-orientated programming language.
The three fundamentals features of an object-oriented programming language are data abstraction, which encapsulates processing with data objects and controls access to data, adds inheritance and dynamic method binding. Inheritance is a powerful concept that greatly enhances the potential reuse of existing software, thereby providing the possibility of significant increases in software development productivity. Dynamic (run-time) method binding allows more flexible use of inheritance.
23. What language was the first to support the three fundamental features of the object-orientated programming?
The first language that supported the three fundamental features of object-oriented programming was Smalltalk. Although Smalltalk never became as widely used as many other languages, support for object-oriented programming is now part of most popular imperative languages, including Ada 95, Java, C++ , and C#.
24. What is an example of two language design criteria that are in direct conflict with each other?
The example of two language design criteria that are in direct conflict with each other are reliability and cost of execution. For example the Java language definition demands that all references to array elements be checked to ensure that the index or indices are in their legal ranges. This step adds a great deal to the cost of execution of Java programs that contain large numbers of references to array elements. C does not require index range checking, so C programs execute faster than semantically equivalent Java programs, although Java programs are more reliable. The designers of Java traded execution efficiency for reliability.
25. What are the three general methods of implementing a programming language?
The three general methods of implementing a programming language are compilation (programs are translated into machine language), pure interpretation (programs are translated by another programs known as interpreter), and Hybrid Implementation (a compromise between compilers and pure interpreter).
26. Which produces faster program execution, a compiler or pure interpreter?
A compiler, as a compiler translates directly into machine code.
27. What role does a symbol table play in a compiler?
The symbol table serves as a database for the compilation process. The primary contents of the symbol table are the type and attribute information of each user-defined name in the program. This information is placed in the symbol table by the lexical and syntax analyzers and is used by the semantic analyzer and the code generator.
28. What does a linker do?
Most user programs also require programs from the operating system. Among the most common of these are programs for input and output. The compiler builds calls to required system programs when they are needed by the user program. Before the machine language programs produced by a compiler can be executed. The required programs from the operating system must be found and linked to the user program. The process of collecting system programs and linking them to user programs is called linking and loading or just linking. in addition user programs may have to be linked to other user programs.
29.Why is the Von Neumann bottleneck important?
The speed of the connection between a computers memory and its processor usually determines the the speed of the computer, because instructions often can be executed faster than they can be moved to the processor for execution. This connection is called the von Neumann bottleneck; it is the primary limiting factor in the speed of von Neuman architecture computers, The von Neumann bottleneck has been one of the primary motivations for the research and development of parallel computers.
30. What are the advantages of implementing a language with pure interpreter?
The advantages of a pure interpreter, is allowing easy implementation of many source level debugging operations, because all run time errors messages can refer to source level units.
1. Why is it useful for a programmer to have some background in language design, even though he or she may never actually design a programming language
Increased capacity to express ideas
Improved background for choosing appropriate languages.
Increased ability to learn new languages.
Better understanding of the significance of an implementation.
2. How can knowledge of programming language characteristics benefit the whole computing community?
If those who choose a language, are better informed, then perhaps better languages would eventually squeeze out poorer ones.
3. What programming language has dominated scientific computing over the past 45 years?
FORTRAN - FORTRAN has been used for a long time for scientific computing. It was the first language for scientific applications because FORTRAN provides efficiency which was the primary concern for scientific applications.
4. What programming language has dominated business applications over the past 45 years?
COBOL - COBOL was the first successful high-level language for business. It is the most commonly used language for business applications because business languages are characterized by facilities for producing elaborate reports, precise ways of describing, strong decimal numbers, character data and the ability to specify decimal arithmetic operations.
5. What programming language has dominated artificial intelligence over the past 45 years?
LISP - LISP which appeared in 1959.Artificial Intelligence (AI) is a broad area of computer applications characterized by the used of symbolic rather than numeric computations.
6. In what language was UNIX written?
The UNIX operating system is written almost entirely in C which has made it relatively easy to port, or move to different machines. Some of the characteristics of C make it a good choice for systems programming. It is low level, execution efficient and doesn’t burden the user with many safety restrictions.
7.What is the disadvantage of having to many features in a language?
If a language has to many features, some programmers wont be familiar with them all, leading to the misuse of some features and disuse of others.
8.How can user-defined operator overloading harm readability of a program?
If a programmer doesn't do it sensibly, it can reduce readability.
9. What is one example of lack of orthogonality in the design of C?
Consider the following rules and exceptions in C. Although C has two kinds of structured data-types arrays and records (structs). records can be any data type except void or a structure of the same type. An array element can be any data type except a void or a function. Parameters are passed by value, unless they are arrays, in which they are , in effect, passed by reference.
10. What language used orthogonality as a primary design criterion?
ALGOL 68 - ALGOL 68 is the most orthogonal programming language because every language constructs in ALGOL 68 has a type, and there are no restrictions on those types. But LISP can also be said as a good combination of simplicity and orthogonality. LISP a functional language is one in which computations are made primarily by applying a function to a given program.
11. What primitive control statement is used to build more complicated control statements in languages that lack them?
It is “goto”, but in the 1970s, the use of “goto” statements was replaced by structured programming, which could be read from top to bottom. (While, in newer languages)
12. What construct of a programming language provides process abstractions?
Programming languages usually contain abstractions for defining and manipulating data structures or controlling the flow of execution. The practical necessity that a programming language supports adequate abstractions is expressed by the abstraction principal. This principle is sometimes formulated as recommendation to the programmer to make proper use of such abstractions.
13.What does it mean for a program to be reliable?
A program is said to be reliable if it performs to its specifications under all conditions. Factors that affect reliability are type checking, exception handling, aliasing, readability and write-ability
14. Why is type checking the parameters of a subprogram important?
Type checking is important because run-time type checking is expensive, compile-time type checking is more desirable. Furthermore, the earlier errors in programs are detected, the less expensive it is to make the required repairs..
15. What is aliasing?
Aliasing is having two or more distinct names that can be used to access the same memory cell. It is now widely accepted that aliasing is a dangerous feature in a programming language. In some languages, aliasing is used to overcome deficiencies in the language’s data abstraction facilities.
16.What is exception handling?
Exception handling is the ability of a program to intercept run-time errors (as well as the unusual conditions detectable by the program), take corrective measures, and then continue in an obvious aid to reliability.
17. Why is reliability important to write-ability?
Readability is important to write-ability because if a programming language is difficult to read and understand then it can be difficult for a programmer to create new code that might need to interact or use other code. Often times code needs to be modified and if a program is difficult to read then it is difficult to add new code to it.
18.How is the cost of compilers for a given language related to the design of that language.
A language that requires many run-time type checks will prohibit fast code execution, regardless of the quality of the compiler.
19. What has been the strongest influence of programming language design over the past 50 years.
Most of the past 50 years have been designed around the prevalent computer architecture, called the von Neumann architecture, after one of its originators, John von Neumann.
20. What is the name of the category of programming languages whose structure is dedicated by the Von Neumann computer architecture?
These languages are called the imperative languages.
21 What two programming language deficiencies were discovered as a result of the research in software development in the 1970s.
The late 1960s and early 70s brought intense analysis of software development. the result in large begun the structure programming movement of both the software development process and program language design.
An important reason for this research was the shift in the major cost of computing from hardware to software. The primary programming language deficiencies that were discovered were in-completeness of type checking and inadequacy of control statements (requiring the extensive use of gotos).
22. What are the three fundamental features of Object-orientated programming language.
The three fundamentals features of an object-oriented programming language are data abstraction, which encapsulates processing with data objects and controls access to data, adds inheritance and dynamic method binding. Inheritance is a powerful concept that greatly enhances the potential reuse of existing software, thereby providing the possibility of significant increases in software development productivity. Dynamic (run-time) method binding allows more flexible use of inheritance.
23. What language was the first to support the three fundamental features of the object-orientated programming?
The first language that supported the three fundamental features of object-oriented programming was Smalltalk. Although Smalltalk never became as widely used as many other languages, support for object-oriented programming is now part of most popular imperative languages, including Ada 95, Java, C++ , and C#.
24. What is an example of two language design criteria that are in direct conflict with each other?
The example of two language design criteria that are in direct conflict with each other are reliability and cost of execution. For example the Java language definition demands that all references to array elements be checked to ensure that the index or indices are in their legal ranges. This step adds a great deal to the cost of execution of Java programs that contain large numbers of references to array elements. C does not require index range checking, so C programs execute faster than semantically equivalent Java programs, although Java programs are more reliable. The designers of Java traded execution efficiency for reliability.
25. What are the three general methods of implementing a programming language?
The three general methods of implementing a programming language are compilation (programs are translated into machine language), pure interpretation (programs are translated by another programs known as interpreter), and Hybrid Implementation (a compromise between compilers and pure interpreter).
26. Which produces faster program execution, a compiler or pure interpreter?
A compiler, as a compiler translates directly into machine code.
27. What role does a symbol table play in a compiler?
The symbol table serves as a database for the compilation process. The primary contents of the symbol table are the type and attribute information of each user-defined name in the program. This information is placed in the symbol table by the lexical and syntax analyzers and is used by the semantic analyzer and the code generator.
28. What does a linker do?
Most user programs also require programs from the operating system. Among the most common of these are programs for input and output. The compiler builds calls to required system programs when they are needed by the user program. Before the machine language programs produced by a compiler can be executed. The required programs from the operating system must be found and linked to the user program. The process of collecting system programs and linking them to user programs is called linking and loading or just linking. in addition user programs may have to be linked to other user programs.
29.Why is the Von Neumann bottleneck important?
The speed of the connection between a computers memory and its processor usually determines the the speed of the computer, because instructions often can be executed faster than they can be moved to the processor for execution. This connection is called the von Neumann bottleneck; it is the primary limiting factor in the speed of von Neuman architecture computers, The von Neumann bottleneck has been one of the primary motivations for the research and development of parallel computers.
30. What are the advantages of implementing a language with pure interpreter?
The advantages of a pure interpreter, is allowing easy implementation of many source level debugging operations, because all run time errors messages can refer to source level units.
Wednesday, 31 December 2014
1.0 - Programming Languages Concepts Notes
Programming Languages Concepts
Sometimes to succeed in something, we need to go back to the basics, to re-develop a solid foundation on which everything else can sit on.
1.1 Reasons for studying the concepts of programming languages
The following is a compelling list of potential benefits for studying concepts of programming.
- Increased capacity to express ideas - Having a better understanding of the concepts of programming languages, will enable a programmer to communicate their thoughts, verbally or in writing.
- Improved background for choosing appropriate languages. When given a choice of programming languages for a new project, many programmers will continue to use the language with which they are most familiar with, even if its poorly suited to the project. If these programmers were familiar with a wider range of languages and language contracts, they would be better able to choose the language that includes the features that best address the characteristics of the problem at hand.
- Increase ability to learn a new languages. Computer programming is still a relatively young discipline and design methodologies, software development tools and programming languages are still in a state of continues evolution. This makes software development an exciting profession, but also means that continues learning is essential. Through understanding of the fundamental concepts of languages, can ease the burden.
|
- Better understanding of the significance of implementation. Helps us understand why programming languages are designed the way they are. Gives us an ability to use a language more intelligently, as it was designed to be. Helps us understand the choices among programming language constructs and the consequences of making those choices.
1.2 Language Evaluation Criteria
How to evaluate programming language via its readability, writ-ability and reliability.Readability
Since maintenance has been recognized as major concept of the software life cycle.The ease of maintenance is determined in a large part by the readability of code. Readability is an important language evaluation criteria.
The bullet points below describe characteristics that contribute to the readability of a programming language
- Overall simplicity, is there a small amount of basic constructs, a small amount of ways to accomplish the same particular operation. Readability problems occur whenever the programs author has learned a different subset from that subset with which the reader is familiar.
- Orthogonality, Meaning that a relativity small set of primitive constructs can be combined in a relatively small number of ways to build the control and data-structures of the language. further more every possible combination of primitives is legal and meaningful. Enables a large amount of data structures can be defined.
- Control Statements, A program that can be read top to bottom is much easier than a program that requires the reader to jump from one statement to some nonadjacent statement in order to follow the execution order. ie. the use of a while loop statement in C, compared to the FORTRAN goto statement.
- Data types and structures, The presence of adequate facilities for defining data types and data structures in a language is another significant aid to readability. For example suppose a numeric type in the language is used for an indicator flag because there is no Boolean type in the language. In such a language, we might have an assignment like 'timeout = 1' whose meaning is unclear vs 'timeout = true' which is clear.
- Syntax design, ie. not restricting a identifier to six characters. using 'end if' instead of just '}'
Writ-ability
The bullet points below describe the most important characteristics influencing the write-ability of a programming language- Simplicity and Orthogonality, If a language has a large number of different constructs, some programmers might not be familiar with all of them. this situation can lead to a misuse of some features and a disuse of others that may be either more elegant or more efficient.
- Support and Abstraction, is the ability to define and then use complicated structures or operations in ways that allow many of the details to be ignored.
- Expressivity, Convenient ways of expressing an operation. like i++ (increment a number)
Reliability
The program is said to be reliable if it performs to its specifications under all conditions.The bullet points below describe several language features that have a significant effect on reliability of programs in a given language.
- Type Checking, simply testing for type errors in a given program, preferable at compile time, as at run-time it can be expensive.
- Exception Handling, the ability of a program to intercept run-time errors. ie javascipt is bad at this.
- Aliasing, is having two or more distinct names that can be used to access the same memory cell. (dangerous feature)
- Readability & Writ-ability, the easier a program is to write, the more likely it is correct, also making it more reliable. Programs that are difficult to read are also difficult to write/modify.
- Cost, the ultimate cost of training programmers to use language.
Effort in writing application.
Cost of executing code, required add on frameworks, environments.
cost of maintainability over a lifetime.
----------------------
The two primary components of a computer are its internal memory and its
processor.
The internal memory is to store programs and data
The processor is a collection of circuits that provides a realization of a set of primitive operations or machine instructions, such as those for arithmetic and logic operations.
The machine language of the computer is a set of instructions.
In absence of other supporting software the machine language is the only language that most computer hardware "understand"
The most practical design choice is to implement hardware with a very low-level language
A language implementation system cannot be the only software on a computer.
An operating system is required supplies higher level primitives then those of a machine language. These primitives provide system resource management, input and output operations, a file management system, text and or program editors and a variety of other commonly needed functions.
The operating
system and language implementations are laid over the machine language
interface of a computer.
Programming
languages can be implemented by any of three general methods.
Compilation
(compiler implementation)
- At one extreme, programs can be translated into machine language, which can be executed directly on the computer.
- Has an advantage of very fast program execution, once translation process is complete.
- Most production implementations of languages such as C are by compilers.
Pure-interpretation
- Opposite end (from compilation) of implementation methods.
- Programs are interpreted by another program called an interpreter, with no translation what so ever.
- The interpreter acts as a simulation of a machine whose fetch-execute cycle deals with high level language program statements rather than machine instructions.
- This software simulation obviously provides a virtual machine for the language.
- Advantage is allowing easy implementation of many source level debugging operations, because all run time errors messages can refer to source level units.
- Disadvantage - runs 10 - 100 times slow than in compiled systems
- Java script and PHP
- Regardless of how many times a statement is executed, it must be decoded every time.
Hybrid
Implementation Systems
- Compromise between compilers and pure interpreters.
- They translate a high level language program to an intermediate language design to allow easy interpretations.
- Makes it faster, because source statements are only decoded once
- A Just In Time (JIT) implementation system initially translates programs to an intermediate language. Then during execution, it compiles intermediate language methods into machine code when they are called. The machine code version is kept for subsequent calls.
- Used with .NET languages , JAVA
- Sometimes an implementer may provide both compiled and interpreted implementation for a language. in these cases, the interpreter is used to develop and debug program. Then after a (relatively) bug free state is reached, the programs are compile to increase their execution speed.
Pre-processors
- A
pre-processor is a program that processes a program immediately before
the program is compiled. Preprocessor instructions are embedded in
programs. Preprocesser instructions are commonly used to specify that
the code from another file is to be included. for example.using mylib.cs
causing the preprocessor to copy the contents of my lib to the top
Subscribe to:
Posts (Atom)