PPL Units (1,2&3)
PPL Units (1,2&3)
UNIT-I
Preliminaries
Topics
1. ReasonsforStudyingConceptsofProgrammingLanguages
2. ProgrammingDomains
3. Language EvaluationCriteria
4. Influences on LanguageDesign
5. Language Categories
6. Language DesignTrade-Offs
7. ImplementationMethods
8. ProgrammingEnvironments
`
Background
―Frankly, we didn‘t have the vaguest idea how the thing [FORTRAN language
andcompiler]wouldworkoutindetail.…Westruckoutsimplytooptimizetheobject
program,therunningtime,becausemostpeopleatthattimebelievedyoucouldn‘tdo that kind of thing. They
believed that machined-coded programs would be so
inefficientthatitwouldbeimpracticalformanyapplications.‖
-John Backus
ProgrammingDomains
• Scientificapplications
– Large number of floating pointcomputations
– Fortran
• Businessapplications
– Produce reports, use decimal numbers andcharacters
– COBOL
• Artificialintelligence
– Symbols rather than numbersmanipulated
– LISP
• Systemsprogramming
– Need efficiency because of continuoususe
– C
• WebSoftware
– Eclecticcollectionoflanguages:markup(e.g.,XHTML),scripting(e.g., PHP), general-
purpose (e.g.,Java)
Language EvaluationCriteria
• Readability:theeasewithwhichprogramscanbereadandunderstood
• Writability:theeasewithwhichalanguagecanbeusedtocreateprograms
• Reliability:conformancetospecifications(i.e.,performstoitsspecifications)
• Cost: the ultimate totalcost
Evaluation Criteria: Readability
• Overallsimplicity
– A manageable set of features andconstructs
– Fewfeaturemultiplicity(meansofdoingthesameoperation)
– Minimal operatoroverloading
• Orthogonality
– Arelativelysmallsetofprimitiveconstructscanbecombinedina relatively small
number ofways
– Every possible combination islegal
• Controlstatements
– Thepresenceofwell-knowncontrolstructures(e.g.,whilestatement)
• Data types andstructures
– Thepresenceofadequatefacilitiesfordefiningdatastructures
• Syntaxconsiderations
– Identifier forms: flexiblecomposition
– Specialwordsandmethodsofformingcompoundstatements
– Formandmeaning:self-descriptiveconstructs,meaningfulkeywords
Evaluation Criteria: Writability
• Simplicity andorthogonality
– Fewconstructs,asmallnumberofprimitives,asmallsetofrulesfor combiningthem
• Support forabstraction
– Theabilitytodefineandusecomplexstructuresoroperationsinways that allow details to
beignored
• Expressivity
– Asetofrelativelyconvenientwaysofspecifyingoperations
– Example:theinclusionofforstatementinmanymodernlanguages
Evaluation Criteria: Reliability
• Typechecking
– Testing for typeerrors
• Exceptionhandling
– Intercept run-time errors and take correctivemeasures
• Aliasing
– Presenceoftwoormoredistinctreferencingmethodsforthesame memorylocation
• Readability andwritability
– A language that does not support ―natural‖ ways of expressing an
algorithmwillnecessarilyuse―unnatural‖approaches,andhencereducedreliability
Evaluation Criteria: Cost
• Training programmers to uselanguage
• Writing programs (closeness to particularapplications)
• Compilingprograms
• Executingprograms
• Languageimplementationsystem:availabilityoffreecompilers
• Reliability: poor reliability leads to highcosts
• Maintainingprograms
Evaluation Criteria: Others
• Portability
• Neural Networks - an OverviewTheeasewithwhichprogramscanbemovedfromoneimplementationto
another
• Generality
– The applicability to a wide range ofapplications
• Well-definedness
– Thecompletenessandprecisionofthelanguage‘sofficialdefinition
Influences on LanguageDesign
• ComputerArchitecture
– Languages are developed around the prevalent computer architecture, known as the von
Neumannarchitecture
• ProgrammingMethodologies
– New software development methodologies (e.g., object-oriented software development) led
to new programming paradigms and by extension, new programming languages
Computer Architecture Influence
• Well-known computer architecture: VonNeumann
• Imperativelanguages,mostdominant,becauseofvonNeumanncomputers
– Data and programs stored inmemory
– Memory is separate fromCPU
– Instructions and data are piped from memory toCPU
– Basis for imperativelanguages
• Variables model memorycells
• Assignment statements modelpiping
• Iteration isefficient
The von NeumannArchitecture
Programming Methodologies Influences
• 1950sandearly1960s:Simpleapplications;worryaboutmachineefficiency
• Late1960s:Peopleefficiencybecameimportant;readability,bettercontrol structures
– structuredprogramming
– top-down design and step-wiserefinement
• Late 1970s: Process-oriented todata-oriented
– dataabstraction
• Middle 1980s: Object-orientedprogramming
– Data abstraction + inheritance +polymorphism
LanguageCategories
• Imperative
– Centralfeaturesarevariables,assignmentstatements,anditeration
– Examples: C,Pascal
• Functional
– Mainmeansofmakingcomputationsisbyapplyingfunctionstogiven parameters
– Examples: LISP,Scheme
• Logic
– Rule-based(rulesarespecifiedinnoparticularorder)
– Example:Prolog
• Object-oriented
– Data abstraction, inheritance, latebinding
– Examples: Java,C++
• Markup
– New;notaprogrammingperse,butusedtospecifythelayoutof information in
Webdocuments
– Examples: XHTML,XML
Language DesignTrade-Offs
ImplementationMethods
• Compilation
– Programs are translated into machinelanguage
• Pure Interpretation
– Programsareinterpretedbyanotherprogramknownasaninterpreter
• Hybrid ImplementationSystems
– A compromise between compilers and pureinterpreters
The operating system and language implementation are layered over Machine interface of a computer
Compilation
• Translate high-level program (source language) into machine code (machine language)
• Slow translation, fastexecution
• Compilation process has severalphases:
– lexical analysis: converts characters in the source program into lexical units
– syntaxanalysis:transformslexicalunitsintoparse treeswhichrepresent the syntactic
structure ofprogram
– Semantics analysis: generate intermediatecode
– code generation: machine code isgenerated
• Loadmodule(executableimage):theuserandsystemcodetogether
• Linkingandloading:theprocessofcollectingsystemprogramandlinkingthem to userprogram
Preprocessors
• Preprocessormacros(instructions)arecommonlyusedtospecifythatcodefrom another file is to
beincluded
• A preprocessor processes a program immediately before the programis compiled to
expand embedded preprocessormacros
• A well-known example: Cpreprocessor
– expands #include, #define, and similarmacros
UNIT-2
Syntax and Semantics
Topics
Introduction
TheGeneralProblemofDescribingSyntax Formal
Methods of Describing Syntax AttributeGrammars
Describing the Meanings of Programs: Dynamic Semantics
Introduction
Syntax:theformorstructureoftheexpressions,statements,andprogram units
Semantics:themeaningoftheexpressions,statements,andprogramunits Syntax and
semantics provide a language‘sdefinition
o Users of a languagedefinition
Other languagedesigners
Implementers
Programmers (the users of thelanguage)
TheGeneralProblemofDescribingSyntax:Terminology
Asentenceisastringofcharactersoversomealphabet A language is
a set ofsentences
Alexemeisthelowestlevelsyntacticunitofalanguage(e.g.,*,sum,begin) A token is a category
of lexemes (e.g.,identifier)
BNF Fundamentals
Non-terminals:BNFabstractions
Terminals:lexemesandtokens
Grammar: a collection of rules
o Examples of BNFrules:
<ident_list> → identifier | identifer, <ident_list>
<if_stmt> → if <logic_expr>then <stmt>
BNF Rules
A rule has a left-hand side (LHS) and a right-hand side (RHS), and consists of
terminal and nonterminal symbols
A grammar is a finite nonempty set of rules
Anabstraction(ornonterminalsymbol)canhavemorethanoneRHS
<stmt> <single_stmt>
|begin <stmt_list>end
Describing Lists
Syntactic lists are described using recursion
<ident_list> ident
| ident, <ident_list>
Aderivationisarepeatedapplicationofrules,startingwiththestartsymbol and ending with a
sentence (all terminalsymbols)
An Example Grammar
<program> <stmts>
<stmts> <stmt>|<stmt> ;<stmts>
<stmt> <var> =<expr>
<var> a|b |c|d
<expr> <term>+<term>|<term>-<term>
<term> <var>|const
An example derivation
<program> =><stmts> =><stmt>
<var> = <expr> => a =<expr>
a = <term> + <term>
a = <var> + <term>
a = b + <term>
a = b + const
Derivation
Every string of symbols in the derivation is a sentential form
Asentenceisasententialformthathasonlyterminalsymbols
A leftmost derivation is one in which the leftmost nonterminal ineach
sentential form is the one that is expanded
A derivation may be neither leftmost nor rightmost
Parse Tree
A hierarchical representation of a derivation
Ambiguity in Grammars
Agrammarisambiguousiffitgeneratesasententialformthathastwoormore distinct parsetrees
Associativity of Operators
Operator associativity can also be indicated by a grammar
AttributeGrammars
Context-freegrammars(CFGs)cannotdescribeallofthesyntaxofprogramming languages
AdditionstoCFGstocarrysomesemanticinfoalongparsetrees Primary value of
attribute grammars(AGs):
o Static semanticsspecification
o Compiler design (static semanticschecking)
Attribute Grammars : Definition
An attribute grammar is a context-free grammar G = (S, N, T, P) with the
following additions:
o ForeachgrammarsymbolxthereisasetA(x)ofattributevalues
o Eachrulehasasetoffunctionsthatdefinecertainattributesofthe nonterminals in therule
o Eachrulehasa(possiblyempty)setofpredicatestocheckforattribute consistency
o Let X0 X1 ... Xn be arule
o FunctionsoftheformS(X0)=f(A(X1),...,A(Xn))definesynthesized attributes
o FunctionsoftheformI(Xj)=f(A(X0),...,A(Xn)),fori<=j<=n,define
inherited attributes
o Initially, there are intrinsic attributes on theleaves
Attribute Grammars: Example
Syntax
<assign> -><var> = <expr>
<expr> -><var> + <var>| <var>
<var> A | B |C
actual_type:synthesizedfor<var>and<expr>expected_type
: inherited for<expr>
Syntaxrule:<expr> <var>[1]+<var>[2]
Semantic rules:
<expr>.actual_type <var>[1].actual_type
Predicate:
<var>[1].actual_type == <var>[2].actual_type
<expr>.expected_type == <expr>.actual_type
Syntaxrule:<var> id
Semantic rule:
<var>.actual_type lookup(<var>.string)
<var>[1].actual_type lookup(A)
<var>[2].actual_type lookup(B)
<var>[1].actual_type =? <var>[2].actual_type
<expr>.actual_type <var>[1].actual_type
<expr>.actual_type =? <expr>.expected_type
Semantics
Thereisnosinglewidelyacceptablenotationorformalismfordescribing semantics
OperationalSemantics
o Describethemeaningofaprogrambyexecutingitsstatementsona machine, either
simulated or actual. The change in the state of the machine (memory, registers, etc.)
defines the meaning of thestatement
Touseoperationalsemanticsforahigh-levellanguage,avirtualmachineis needed
Ahardwarepureinterpreterwouldbetooexpensive
Asoftwarepureinterpreteralsohasproblems:
o Thedetailedcharacteristicsoftheparticularcomputerwouldmake actions difficult
tounderstand
o Such a semantic definition would be machine-dependent
Operational Semantics
A better alternative: A completecomputersimulation The process:
o Buildatranslator(translatessourcecodetothemachinecodeofan idealizedcomputer)
o Buildasimulatorfortheidealizedcomputer Evaluation
of operationalsemantics:
o Good if used informally (language manuals,etc.)
o Extremelycomplexifusedformally(e.g.,VDL),itwasusedfordescribing semantics ofPL/I.
Axiomatic Semantics
o Based on formal logic (predicatecalculus)
o Original purpose: formal programverification
o Approach:Defineaxiomsorinferencerulesforeachstatementtypein the language (to
allow transformations of expressions to other expressions)
o The expressions are calledassertions
Axiomatic Semantics
Anassertionbeforeastatement(aprecondition)statestherelationshipsand
constraintsamongvariablesthataretrueatthatpointinexecution
An assertion following a statement is a postcondition
Aweakestpreconditionistheleastrestrictivepreconditionthatwillguarantee thepostcondition
Pre-postform:{P}statement{Q}
An example: a = b + 1 {a > 1}
Onepossibleprecondition:{b>10} Weakest
precondition: {b>0}
Anaxiomforassignmentstatements (x =E):
{Qx->E }x=E{Q}
Characteristicsoftheloopinvariant
Imustmeetthefollowingconditions:
o P=>I (the loop invariant must be trueinitially)
o {I}B{I} (evaluation of the Boolean mustnot
change the validity of I)
o {IandB}S{I} (I is not changed by executingthe
body of the loop)
o (Iand(notB))=>Q (if I is true and B is false,Q
is implied)
o Theloopterminates (this can be difficult toprove)
TheloopinvariantIisaweakenedversionofthelooppostcondition,anditis also aprecondition.
Imustbeweakenoughtobesatisfiedpriortothebeginningoftheloop,but
whencombinedwiththeloopexitcondition,itmustbestrongenoughtoforce the truth of
thepostcondition
Evaluation of axiomaticsemantics:
o Developingaxiomsorinferencerulesforallofthestatementsina language isdifficult
o Itisagoodtoolforcorrectnessproofs,andanexcellentframeworkfor
reasoningaboutprograms,butitisnotasusefulforlanguageusersand compilerwriters
o Itsusefulnessindescribingthemeaningofaprogramminglanguageis limited for language
users or compilerwriters
Denotational Semantics
o Based on recursive functiontheory
o The most abstract semantics descriptionmethod
o Originally developed by Scott and Strachey(1970)
o Theprocessofbuildingadenotationalspecforalanguage(not necessarilyeasy):
Defineamathematicalobjectforeachlanguageentity
Defineafunctionthatmapsinstancesofthelanguageentities
ontoinstancesofthecorrespondingmathematicalobjects
o Themeaningoflanguageconstructsaredefinedbyonlythevaluesofthe program'svariables
o Thedifferencebetweendenotationalandoperationalsemantics:In operational
semantics, the state changes are defined by coded
algorithms;indenotationalsemantics,theyaredefinedbyrigorous
mathematicalfunctions
o Thestateofaprogramisthevaluesofallitscurrentvariables
s={<i1,v1>,<i2,v2>,…,<in,vn>}
<dec_num> 0|1|2|3|4|5|6|7|8|9
| <dec_num> (0 | 1 | 2 | 3 | 4 |
5 | 6 | 7 | 8 | 9)
Expressions
MapexpressionsontoZ {error}
Weassumeexpressionsaredecimalnumbers,variables,orbinaryexpressions
havingonearithmeticoperatorandtwooperands,eachofwhichcanbean expression
Me(<expr>,s) =
case <expr>of
<dec_num> => Mdec(<dec_num>, s)
<var> =>
if VARMAP(<var>, s) == undefthen
error
else VARMAP(<var>, s)
<binary_expr> =>
if (Me(<binary_expr>.<left_expr>, s) == undef
OR Me(<binary_expr>.<right_expr>, s) =
undef)then
error
else
if(<binary_expr>.<operator>==‗+‘then
Me(<binary_expr>.<left_expr>, s)+
Me(<binary_expr>.<right_expr>, s) else
Me(<binary_expr>.<left_expr>, s) *
Me(<binary_expr>.<right_expr>,s)
...
Assignment Statements
o Maps state sets to statesets
Ma(x :=E,s) =
ifMe(E,s)==error
thenerror
else s‘ = {<i1‘,v1‘>,<i2‘,v2‘>,...,<in‘,vn‘>}, where
for j = 1, 2, ..., n,
vj‘ = VARMAP(ij, s) if ij <> x
=Me(E,s)ifij==x
Logical PretestLoops
o Maps state sets to statesets
Ml(whileBdoL,s) =
if Mb(B, s) ==
undefthenerror
elseifMb(B,s)==false thens
elseifMsl(L,s)==error
thenerror
else Ml(while B do L, Msl(L, s))
The meaning of the loop is the value of the program variables after the
statementsintheloophavebeenexecutedtheprescribednumberoftimes, assuming there have
been noerrors
Inessence,theloophasbeenconvertedfromiterationtorecursion,wherethe
recursivecontrolismathematicallydefinedbyotherrecursivestatemapping functions
Recursion,whencomparedtoiteration,iseasiertodescribewithmathematical rigor
Evaluation of denotational semantics
o Can be used to prove the correctness ofprograms
o Provides a rigorous way to think aboutprograms
o Can be an aid to languagedesign
o Has been used in compiler generationsystems
o Becauseofitscomplexity,theyareoflittleusetolanguageusers
Summary
BNF and context-free grammars are equivalent meta-languages
o Well-suitedfordescribingthesyntaxofprogramminglanguages
Anattributegrammarisadescriptiveformalismthatcandescribeboththe syntax and the
semantics of alanguage
Three primary methods of semantics description
o Operation, axiomatic,denotational
UNIT-III
Data types
Topics
• Introduction
• Primitive DataTypes
• Character StringTypes
• User-Defined OrdinalTypes
• ArrayTypes
• AssociativeArrays
• RecordTypes
• UnionTypes
• Pointer and ReferenceTypes
• Names
• Variables
• The Concept ofBinding
• TypeChecking
• StrongTyping
• TypeCompatibility
• Scope
• Scope andLifetime
• ReferencingEnvironments
• NamedConstants
Introduction
• A data type defines a collection of data objects and a set of predefined operations on
thoseobjects
• A descriptor is the collection of the attributes of avariable
• Anobjectrepresentsaninstanceofauser-defined(abstractdata)type
• Onedesignissueforalldatatypes:Whatoperationsaredefinedandhoware theyspecified?
Primitive Data Types
• Almostallprogramminglanguagesprovideasetofprimitivedatatypes
• Primitivedatatypes:Thosenotdefinedintermsofotherdatatypes
• Someprimitivedatatypesaremerelyreflectionsofthehardware
• Othersrequireonlyalittlenon-hardwaresupportfortheirimplementation
Primitive Data Types:Integer
• Almostalwaysanexactreflectionofthehardwaresothemappingistrivial
• Theremaybeasmanyaseightdifferentintegertypesinalanguage
• Java‘s signed integer sizes: byte, short, int,long
Primitive Data Types: Floating Point
• Model real numbers, but only asapproximations
• Languages for scientific use support at least two floating-point types (e.g., float and double;
sometimesmore
• Usually exactly like the hardware, but notalways
• IEEE Floating-Point
Standard754
Subrange Types
• An ordered contiguous subsequence of an ordinaltype
–Example: 12..18 is a subrange of integer type
• Ada‘sdesign
typeDaysis(mon,tue,wed,thu,fri,sat,sun); subtype
Weekdays is Days range mon..fri;
subtypeIndexisIntegerrange1..100;
Subrange Evaluation
• Aid toreadability
–Makeitcleartothereadersthatvariablesofsubrangecanstoreonly certain range ofvalues
• Reliability
–as Assigning
anerror
a value to a subrange variable that is outside thespecified range is detected
Array Types
• An array is an aggregate of homogeneous data elements in which an
individualelementisidentifiedbyitspositionintheaggregate,relativetothe firstelement.
• FORTRAN, C: integeronly
• Ada: integer or enumeration (includes Boolean andchar)
• Java: integer typesonly
• Index rangechecking
- C,C++,Perl,andFortrandonotspecify
rangechecking
- Java, ML, C# specify rangechecking
- InAda,thedefaultistorequirerange
checking,butitcanbeturnedoff
• Static:subscriptrangesarestaticallyboundandstorageallocationisstatic (beforerun-time)
–CharacterstringsinCandC++
charname[]=―freddie‖;
Heterogeneous Arrays
• A heterogeneous array is one in which the elements need not be of the same type
• Supported by Perl, Python, JavaScript, andRuby
Arrays Operations
•APLprovidesthemostpowerfularrayprocessingoperationsforvectorsand
matrixesaswellasunaryoperators(forexample,toreversecolumnelements)
Implementation of Arrays
• Accessfunctionmapssubscriptexpressionstoanaddressinthearray
Slice Examples
• Fortran95
Integer, Dimension (10) ::Vector
Integer,Dimension(3,3)::Mat
Integer,Dimension(3,3)::Cube
Vector(3:6)isafourelementarray
Compile-Time Descriptors
Associative Arrays
• An associative array is an unordered collection of data elements that are indexed by an
equal number of values calledkeys
–Elementscanberemovedwithdelete
delete$hi_temps{"Tue"};
Record Types
• Arecordisapossiblyheterogeneousaggregateofdataelementsinwhichthe individual elements are
identified bynames
• Designissues:
–What is the syntactic form of references to the field?
–Are elliptical references allowed
Definition of Records in COBOL
• COBOL uses level numbers to show nested records; others use recursive definition
01 EMP-REC.
02 EMP-NAME.
05 FIRST PIC X(20).
05MID PICX(10).
05 LAST PIC X(20).
02 HOURLY-RATE PIC 99V99.
References to Records
• Record fieldreferences
1. COBOL
field_name OF record_name_1 OF ... OF record_name_n
2. Others (dotnotation)
record_name_1.record_name_2. ... record_name_n.field_name
Operations on Records
• Assignment is very common if the types areidentical
• Ada allows recordcomparison
• Ada records can be initialized with aggregateliterals
• COBOL provides MOVECORRESPONDING
–Evaluation
Copies a field of the source record to the corresponding field in the target record
and Comparison to Arrays
• Recordsareusedwhencollectionofdatavaluesisheterogeneous
• Accesstoarrayelementsismuchslowerthanaccesstorecordfields,because subscripts are dynamic
(field names arestatic)
• Dynamic subscripts could be used with record field access, but it would disallow type
checking and it would be muchslower
Implementation of RecordType
Unions Types
• Aunionisatypewhosevariablesareallowedtostoredifferenttypevaluesat different times
duringexecution
• Designissues
–Should type checking be required?
–Should unions be embedded in records?
Discriminated vs. FreeUnions
• Fortran,C,andC++provideunionconstructsinwhichthereisnolanguage
supportfortypechecking;theunionintheselanguagesiscalledfreeunion
• Type checking of unions require that each union include a type indicator called
adiscriminant
–Supported by Ada
Ada Union Types
type Shape is (Circle, Triangle, Rectangle); type
Colors is (Red, Green,Blue);
type Figure (Form: Shape) isrecord Filled:
Boolean;
Color: Colors;
case Form is
whenCircle=>Diameter:Float; when
Triangle=>
Leftside, Rightside: Integer; Angle:
Float;
when Rectangle => Side1, Side2: Integer;
end
case;end record;
• A pointer type variable has a range of values that consists of memory addresses and a special
value,nil
• Provide the power of indirectaddressing
• Provideawaytomanagedynamicmemory
• A pointer can be used to access a location in the area where storage is dynamically created
(usually called aheap)
• Dangling pointers(dangerous)
–A pointer points to a heap-dynamic variable that has been deallocated
• Lost heap-dynamicvariable
–An allocated heap-dynamic variable that is no longer accessible to the user
program (often called garbage)
• Pointerp1issettopointtoanewlycreatedheap-dynamicvariable
• Pointer p1 is later set to point to another newly created heap-dynamic variable
• Theprocessoflosingheap-dynamicvariablesiscalledmemoryleakage
Pointers in Ada
• Some dangling pointers are disallowed because dynamic objects can be
automaticallydeallocatedattheendofpointer'stypescope
• The lost heap-dynamic variable problem is not eliminated by Ada (possible
withUNCHECKED_DEALLOCATION)
Reference Types
• C++ includes a special kind of pointer type called a reference type that is used primarily for
formalparameters
–Advantages of both pass-by-reference and pass-by-value
• JavaextendsC++‘sreferencevariablesandallowsthemtoreplacepointers entirely
–References are references to objects, rather than being addresses
• C#includesboththereferencesofJavaandthepointersofC++
Evaluation of Pointers
• Danglingpointersanddanglingobjectsareproblemsasisheapmanagement
• Pointersarelikegoto's--theywidentherangeofcellsthatcanbeaccessedby avariable
• Pointersorreferencesarenecessaryfordynamicdatastructures--sowecan't design a language
withoutthem
Representations of Pointers
• Large computers use singlevalues
• Intel microprocessors use segment andoffset
Dangling Pointer Problem
• Tombstone:extraheapcellthatisapointertotheheap-dynamicvariable
–The actual pointer variable points only at tombstones
–When heap-dynamic variable de-allocated, tombstone remains but set to nil
–Costly in time and space
. Locks-and-keys: Pointer values are represented as (key, address) pairs
–Heap-dynamicvariablesarerepresentedasvariablepluscellforintegerlock value
–When heap-dynamic variable allocated, lock value is created and placed in lock cell and key
cell of pointer
Heap Management
• A very complex run-timeprocess
• Single-size cells vs. variable-sizecells
• Two approaches to reclaimgarbage
–Reference counters (eager approach): reclamation is gradual
–Mark-sweep (lazy approach): reclamation occurs when the list of variable space
becomesempty
Reference Counter
• Referencecounters:maintainacounterineverycellthatstorethenumberof pointers currently
pointing at thecell
–circularly
Disadvantages: space required, execution time required, complications for cells connected
Mark-Sweep
•The run-time system allocates storage cells as requested and disconnects pointers from cells as
necessary; mark-sweep thenbegins
Marking Algorithm
Length
If too short, they cannot beconnotative
Languageexamples:
FORTRAN I: maximum6
COBOL: maximum30
FORTRAN 90 and ANSI C: maximum31
Ada and Java: no limit, and all aresignificant
C++: no limit, but implementors often imposeone
Connectors
Pascal, Modula-2, and FORTRAN 77 don'tallow
Othersdo
Casesensitivity
Disadvantage: readability (names that look alike aredifferent)
worse in C++ and Java because predefined names are mixed case(e.g.
IndexOutOfBoundsException)
C, C++, and Java names are casesensitive
The names in other languages arenot
Specialwords
An aid to readability; used to delimit or separate statementclauses
Def: A keyword is a word that is special only in certain contexts i.e. in Fortran:
Real VarName (Real is data type followed with a name, therefore Real is a keyword)
Real = 3.4 (Real is avariable)
Disadvantage: poorreadability
Def: A reserved word is a special word that cannot be used as a user-defined
name
Variables
A variable is an abstraction of a memorycell
Variables can be characterized as a sextuple ofattributes:
(name, address, value, type, lifetime, andscope)
Name - not all variables have them(anonymous)
Address - the memory address with which it is associated (also calledl-value)
A variable may have different addresses at different times duringexecution
A variable may have different addresses at different places in aprogram
If two variable names can be used to access the same memory location, they are
calledaliases
Aliases are harmful to readability (program readers must remember all ofthem)
How aliases can becreated:
Pointers, reference variables, C and C++ unions, (and through parameters-
discussed in Chapter9)
Some of the original justifications for aliases are no longer valid; e.g. memory
reuse inFORTRAN
Replace them with dynamicallocation
Type - determines the range of values of variables and the set of operations that are
defined for values of that type; in the case of floating point, type also determines the
precision
Value - the contents of the location with which the variable isassociated
Abstract memory cell - the physical cell or collection of cells associated with a
variable
Type Checking
Generalize the concept of operands and operators to include subprograms and
assignments
Type checking is the activity of ensuring that the operands of an operator are of
compatibletypes
A compatible type is one that is either legal for the operator, or is allowed under
language rules to be implicitly converted, by compiler- generated code, to a legal
type. This automatic conversion is called acoercion.
A type error is the application of an operator to an operand of aninappropriate
type
If all type bindings are static, nearly all type checking can bestatic
If type bindings are dynamic, type checking must bedynamic
Def:Aprogramminglanguageisstronglytypediftypeerrorsarealwaysdetected
Strong Typing
Advantage of strong typing: allows the detection of the misuses of variables that
result in typeerrors
Languageexamples:
FORTRAN 77 is not: parameters,EQUIVALENCE
Pascal is not: variantrecords
C and C++ are not: parameter type checking can be avoided; unions are not
typechecked
Ada is, almost (UNCHECKED CONVERSION is loophole)
(Java is similar)
Coercion rules strongly affect strong typing--they can weaken it considerably (C++
versusAda)
Although Java has just half the assignment coercions of C++, its strong typing is
still far less effective than that ofAda
Type Compatibility
Our concern is primarily for structuredtypes
Def: Name type compatibility means the two variables have compatible types if
they are in either the same declaration or in declarations that use the same type
name
Easy to implement but highlyrestrictive:
Subranges of integer types are not compatible with integertypes
Formal parameters must be the same type as their corresponding actual
parameters (Pascal)
Structure type compatibility means that two variables have compatible types if their
types have identicalstructures
More flexible, but harder toimplement
Consider the problem of two structuredtypes:
Are two record types compatible if they are structurally the same but use
different fieldnames?
Are two array types compatible if they are the same except that the subscripts
aredifferent?
(e.g. [1..10] and [0..9])
Are two enumeration types compatible if their components are spelled
differently?
With structural type compatibility, you cannot differentiate between types of
thesamestructure (e.g. different units of speed, bothfloat)
Languageexamples:
Pascal: usually structure, but in some cases name is used (formalparameters)
C: structure, except forrecords
Ada: restricted form ofname
Derived types allow types with the same structure to bedifferent
Anonymous types are all unique, evenin:
A, B : array (1..10) of INTEGER:
Scope
The scope of a variable is the range of statements over which it isvisible
The nonlocal variables of a program unit are those that are visible but not declared
there
The scope rules of a language determine how references to names are associated
withvariables
Staticscope
Based on programtext
To connect a name reference to a variable, you (or the compiler) must findthe
declaration
Search process: search declarations, first locally, then in increasinglylarger
enclosing scopes, until one is found for the givenname
Enclosingstaticscopes(toaspecificscope)arecalleditsstaticancestors;the
nearest static ancestor is called a staticparent
Variables can be hidden from a unit by having a "closer" variable with the same
name
C++ and Ada allow access to these "hidden"variables
In Ada:unit.name
In C++:class_name::name
Blocks
A method of creating static scopes inside program units--from ALGOL60
Examples:
C and C++: for (...)
{
int index;
...
}
Ada: declare LCL : FLOAT;
begin
...
end
Evaluation of StaticScoping
Consider theexample:
Assume MAIN calls A and B
A calls C and D
B calls A and E
Static Scope Example
Static Scope Example
Static Scope
Suppose the spec is changed so that D must now access some data inB
Solutions:
Put D in B (but then C can no longer call it and D cannot access A'svariables)
Move the data from B that D needs to MAIN (but then all procedures can access
them)
Same problem for procedureaccess
Overall: static scoping often encourages manyglobals
DynamicScope
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 thispoint
Scope Example
MAIN
- declaration of x
SUB1
- declaration of x -
...
call SUB2
...
SUB2
...
- reference to x -
...
...
call SUB1
…
Scope Example
Staticscoping
Reference to x is to MAIN'sx
Dynamic scoping
Reference to x is to SUB1'sx
Evaluation of DynamicScoping:
Advantage:convenience
Disadvantage: poorreadability
Named Constants
Def: A named constant is a variable that is bound to a value only when it is bound
tostorage
Advantages: readability andmodifiability
Used to parameterizeprograms
The binding of values to named constants can be either static (calledmanifest
constants) ordynamic
Languages:
Pascal: literalsonly
FORTRAN 90: constant-valuedexpressions
Ada, C++, and Java: expressions of any kind
VariableInitialization
Def: The binding of a variable to a value at the time it is bound to storage is called
initialization
Initialization is often done on the declarationstatement
e.g.,Java
int sum = 0;
Summary
• The data types of a language are a large part of what determines that language‘s style and
usefulness
• The user-defined enumeration and subrange types are convenient and add to the readability
and reliability of programs
• Pointers are used for addressing flexibility and to control dynamic storage management
Variables are characterized by the sextuples: name, address, value, type, lifetime,
scope
Scalar variables are categorized as: static, stack dynamic, explicit heap dynamic,
implicit heapdynamic
UNIT-IV
Expressions and Statements
• Introduction
• ArithmeticExpressions
• OverloadedOperators
• TypeConversions
• Relational and BooleanExpressions
• Short-CircuitEvaluation
• AssignmentStatements
• Mixed-ModeAssignment
• ControlStructures
• Introduction
• SelectionStatements
• IterativeStatements
• UnconditionalBranching
• GuardedCommands
• Conclusions
Introduction
• Expressions are the fundamental means of specifying computations in a programminglanguage
• Tounderstandexpressionevaluation,needtobefamiliarwiththeordersof operator and
operandevaluation
• Essenceofimperativelanguagesisdominantroleofassignmentstatements
ArithmeticExpressions
• Arithmeticevaluationwasoneofthemotivationsforthedevelopmentofthe first
programminglanguages
• Arithmetic expressions consist of operators, operands, parentheses, and functioncalls
Arithmetic Expressions: DesignIssues
• Designissuesforarithmeticexpressions
–Operator precedence rules?
–Operator associativity rules?
–Order of operand evaluation?
–Operand evaluation side effects?
–Operator overloading?
–Type mixing in expressions?
Arithmetic Expressions: Operators
• A unary operator has oneoperand
• A binary operator has twooperands
• A ternary operator has threeoperands
Arithmetic Expressions: Operator Precedence Rules
• The operator precedence rules for expression evaluation define the order in
which―adjacent‖operatorsofdifferentprecedencelevelsareevaluated
• Typical precedencelevels
– parentheses
– unaryoperators
– ** (if the language supportsit)
–*, /
– +,-
Arithmetic Expressions: Operator Associativity Rule
• The operator associativity rules for expression evaluation define the order in
whichadjacentoperatorswiththesameprecedencelevelareevaluated
• Typical associativityrules
–Left to right, except **, which is right to left
–Sometimes unary operators associate right to left (e.g., in FORTRAN)
• APL is different; all operators have equal precedence and all operators associate right toleft
• Precedence and associativity rules can be overriden with parentheses Arithmetic
Expressions: ConditionalExpressions
• ConditionalExpressions
–C-basedlanguages(e.g.,C,C++)
–Anexample:
average = (count == 0)? 0 : sum / count
–Limitationsofcomputerarithmetic e.g.overflow
• Often ignored by the run-timesystem
Relational and BooleanExpressions
• RelationalExpressions
–Use relational operators and operands of varioustypes
–Evaluate to some Boolean representation
–Operatorsymbolsusedvarysomewhatamonglanguages(!=,/=,.NE.,<>,#)
• JavaScriptandPHPhavetwoadditionalrelationaloperator,===and!==
- Similar to their cousins, == and !=, except that they do not coerce their operands
• BooleanExpressions
–Operands are Boolean and the result is Boolean
–Example operators
FORTRAN77 FORTRAN 90 C Ada
.AND. and && and
.OR. or || or
.NOT. not ! not
xor
Relational and Boolean Expressions: No Boolean Type in C
• C89 has no Boolean type--it uses int type with 0 for false and nonzero for true
• One odd characteristic of C‘sexpressions: a < b <c is a legal
expression, but the result is not what you mightexpect:
Whichisequivalentto
if($flag){
$total = 0
} else {
$subtotal = 0
}
is writtenas a
+= b
ch = getchar() is carried out; the result (assigned to ch) is used as a conditional value for
the while statement
List Assignments
• PerlandRubysupportlistassignments e.g.,
($first, $second, $third) = (20, 30, 40);
Mixed-Mode Assignment
• Assignmentstatementscanalsobemixed-mode,forexample int a,b;
float c;
c = a / b;
• In Fortran, C, and C++, any numeric type value can be assigned to any numeric typevariable
• In Java, only widening assignment coercions aredone
• In Ada, there is no assignmentcoercion
Levels of ControlFlow
–Withinexpressions
–Amongprogramunits
–Amongprogramstatements
Control Statements: Evolution
• FORTRANIcontrolstatementswerebaseddirectlyonIBM704hardware
• Much research and argument in the 1960s about theissue
–flowchartscanbecodedwithonlytwo-wayselectionandpretestlogicalloops
One important result: It was proven that all algorithms represented by
Control Structure
• Acontrolstructureisacontrolstatementandthestatementswhoseexecution itcontrols
• Designquestion
–Should a control structure have multiple entries?
Selection Statements
• A selection statement provides the means of choosing between two or more paths
ofexecution
• Two generalcategories:
–Two-way selectors
–Multiple-way selectors
Two-Way Selection Statements
• Generalform:
if control_expressionthen
clause else clause
• DesignIssues:
–What is the form and type of the controlexpression?
–How are the then and else clauses specified?
–How should the meaning of nested selectors be specified?
The Control Expression
• If the then reserved word or some other syntactic marker is not used to
introducethethenclause,thecontrolexpressionisplacedinparentheses
• InC89,C99,Python,andC++,thecontrolexpressioncanbearithmetic
• In languages such as Ada, Java, Ruby, and C#, the control expressionmust beBoolean
Clause Form
• In many contemporary languages, the then and else clauses can be single statements or
compoundstatements
• InPerl,allclausesmustbedelimitedbybraces(theymustbecompound)
• InFortran95,Ada,andRuby,clausesarestatementsequences
• Pythonusesindentationtodefineclauses if x >y:
x=y
print "case 1"
Nesting Selectors
• Javaexample
if(sum==0)
if(count==0)
result=0;
elseresult=1;
• Which if gets theelse?
• Java'sstaticsemanticsrule:elsematcheswiththenearestif Nesting
Selectors(continued)
• Toforceanalternativesemantics,compoundstatementsmaybeused: if (sum == 0){
if(count==0)
result =0;
}
else result = 1;
• The above solution is used in C, C++, andC#
• Perlrequiresthatallthenandelseclausestobecompound
• Statementsequencesasclauses:Ruby if sum ==
0then
ifcount==0then result
=0
else
result=1
end
end
• Python
if sum == 0 :
ifcount==0:
result =0
else :
result=1
- Each selectable segment must end with an unconditional branch (gotoor break)
• Ada
case expression is
when choice list =>stmt_sequence;
…
when choice list =>stmt_sequence; when
others =>stmt_sequence;]
end case;
• MorereliablethanC‘sswitch(onceastmt_sequenceexecutioniscompleted,
controlispassedtothefirststatementafterthecasestatement
• Ada designchoices:
1. Expression can be any ordinaltype
2. Segments can be single orcompound
3. Onlyonesegmentcanbeexecutedperexecutionoftheconstruct
4. Unrepresented values are notallowed
• Constant ListForms:
1. A list ofconstants
2. Caninclude:
- Subranges
- BooleanORoperators(|)
Iterative Statements
• The repeated execution of a statement or compound statement is
accomplished either by iteration orrecursion
• General design issues for iteration controlstatements:
1. How is iterationcontrolled?
2. Where is the control mechanism in theloop?
Counter-Controlled Loops
• Acountingiterativestatementhasaloopvariable,andameansofspecifying the initial and
terminal, and stepsizevalues
• DesignIssues:
• What are the type and scope of the loopvariable?
• Whatisthevalueoftheloopvariableatlooptermination?
• Shoulditbelegalfortheloopvariableorloopparameterstobechangedin
theloopbody,andifso,doesthechangeaffectloopcontrol?
• Should the loop parameters be evaluated only once, or once for every iteration?
Iterative Statements: Examples
• FORTRAN 95syntax
DO label var = start, finish [, stepsize]
• Stepsize can be any value butzero
• Parameters can beexpressions
• Designchoices:
1. Loop variable must beINTEGER
2. Loop variable always has its lastvalue
3. The loop variable cannot be changed in the loop, but the parameters can;
becausetheyareevaluatedonlyonce,itdoesnotaffectloopcontrol
4. Loop parameters are evaluated onlyonce
• FORTRAN 95 : a secondform:
[name:] Do variable = initial, terminal [,stepsize]
… End
Do [name]
• Ada
forvarin[reverse]discrete_rangeloop ...
endloop
• Designchoices:
- Typeoftheloopvariableisthatofthediscreterange(Adiscreterangeisa sub-range of an integer or
enumerationtype).
- Loop variable does not exist outside theloop
- Theloopvariablecannotbechangedintheloop,butthediscreterangecan; it does not affect
loopcontrol
- The discrete range is evaluated justonce
• Cannot branch into the loopbody
• C-basedlanguages
for ([expr_1] ; [expr_2] ; [expr_3]) statement
- Theexpressionscanbewholestatements,orevenstatementsequences, with the statements
separated bycommas
–The value of a multiple-statement expression is the value of the last statement in the expression
–If the second expression is absent, it is an infinite loop
• Designchoices:
- There is no explicit loopvariable
- Everything can be changed in theloop
- Thefirstexpressionisevaluatedonce,buttheothertwoareevaluatedwith eachiteration
• C#‘s foreach statement iterates on the elements of arrays and other collections:
Strings[] = strList = {"Bob", "Carol", "Ted"}; foreach
(Strings name in strList)
Console.WriteLine ("Name: {0}", name);
Topics
• Introduction
• Fundamentals ofSubprograms
• Design Issues forSubprograms
• Local ReferencingEnvironments
• Parameter-PassingMethods
• Parameters That Are SubprogramNames
• OverloadedSubprograms
• GenericSubprograms
• Design Issues forFunctions
• User-Defined OverloadedOperators
• Coroutines
Introduction
• Two fundamental abstractionfacilities
–Process abstraction
• Emphasized from earlydays
–Data abstraction
• Emphasized inthe1980s
Fundamentals of Subprograms
• Each subprogram has a single entrypoint
• Thecallingprogramissuspendedduringexecutionofthecalledsubprogram
• Controlalwaysreturnstothecallerwhenthecalledsubprogram‘sexecution terminates
Basic Definitions
• Asubprogramdefinition describestheinterfacetoandtheactionsofthe
subprogramabstraction
• Asubprogramcallisanexplicitrequestthatthesubprogrambeexecuted
• Asubprogramheaderisthefirstpartofthedefinition,includingthename, the kind of
subprogram, and the formalparameters
• Theprotocolisasubprogram‘sparameterprofileand,ifitisafunction,its returntype
• FunctiondeclarationsinCandC++areoftencalledprototypes
• Asubprogramdeclarationprovidestheprotocol,butnotthebody,ofthe subprogram
• Aformalparameter isadummyvariablelistedinthesubprogramheaderand used in
thesubprogram
• Anactualparameterrepresentsavalueoraddressusedinthesubprogram callstatement
Actual/Formal Parameter Correspondence
• Positional
–firstactualparameterisboundtothefirstformalparameterandsoforth
Thebindingofactualparameterstoformalparametersisbyposition:the
–positionallyassociated
InC++,defaultparametersmustappearlastbecauseparametersare
• C#methodscanacceptavariablenumberofparametersaslongastheyare of the sametype
Procedures and Functions
• There are two categories ofsubprograms
–Proceduresarecollectionofstatementsthatdefineparameterized computations
Functionsstructurallyresembleproceduresbutaresemanticallymodeledon
–
mathematicalfunctions
• Sometimes calledpass-by-copy
• Disadvantages:
–Thoseofpass-by-result
–Thoseofpass-by-value
Pass-by-Reference (Inout Mode)
• Pass an accesspath
• Also calledpass-by-sharing
• Passingprocessisefficient(nocopyingandnoduplicatedstorage)
• Disadvantages
–Sloweraccesses(comparedtopass-by-value)toformalparameters
–Potentialsforun-wantedsideeffects
–Un-wantedaliases(accessbroadened)
Pass-by-Name (Inout Mode)
• By textualsubstitution
• Formalsareboundtoanaccessmethodatthetimeofthecall,butactual binding to a value or
address takes place at the time of a reference or assignment
• Allows flexibility in latebinding
Implementing Parameter-Passing Methods
• Inmostlanguageparametercommunicationtakesplacethrutherun-time stack
• Pass-by-referencearethesimplesttoimplement;onlyanaddressisplacedin thestack
• Asubtlebutfatalerrorcanoccurwithpass-by-referenceandpass-by-value- result: a formal
parameter corresponding to a constant can mistakenly be changed
• Ada
–Threesemanticsmodesofparametertransmission:in,out,inout;inisthe defaultmode
–Formalparametersdeclaredoutcanbeassignedbutnotreferenced;those
declaredincanbereferencedbutnotassigned;inoutparameterscanbe referenced andassigned
• C#
–Default method: pass-by-value
–Pass-by-referenceisspecifiedbyprecedingbothaformalparameterandits actual parameter
withref
• PHP: very similar toC#
• Perl:allactualparametersareimplicitlyplacedinapredefinedarraynamed @_
Type Checking Parameters
• Considered very important forreliability
• FORTRAN 77 and original C:none
• Pascal,FORTRAN90,Java,andAda:itisalwaysrequired
• ANSI C and C++: choice is made by theuser
–Prototypes
• RelativelynewlanguagesPerl,JavaScript,andPHPdonotrequiretype checking
Multidimensional Arrays asParameters
• Ifamultidimensionalarrayispassedtoasubprogramandthesubprogram
isseparatelycompiled,thecompilerneedstoknowthedeclaredsizeofthat array to build the storage
mappingfunction
• Formalparameterthatarearrayshaveadeclarationaftertheheader
–Forsingle-dimensionarrays,thesubscriptisirrelevant
–Formulti-dimensionalarrays,thesubscriptsallowthestorage-mapping function
Multidimensional Arrays as Parameters: Java and C#
• Similar toAda
• Arraysareobjects;theyareallsingle-dimensioned,buttheelementscanbe arrays
• Eacharrayinheritsanamedconstant(lengthinJava,LengthinC#)thatis
settothelengthofthearraywhenthearrayobjectiscreated Design
Considerations for ParameterPassing
• Two importantconsiderations
–Efficiency
–One-way or two-way data transfer
• But the above considerations are inconflict
–wheneverpossible
Goodprogrammingsuggestlimitedaccesstovariables,whichmeansone- way
Generic Subprograms
• Agenericorpolymorphicsubprogramtakesparametersofdifferenttypeson
differentactivations
• Overloaded subprograms provide ad hocpolymorphism
• Asubprogramthattakesagenericparameterthatisusedinatype
expressionthatdescribesthetypeoftheparametersofthesubprogram provides
parametricpolymorphism
• Theabovetemplatecanbeinstantiatedforanytypeforwhichoperator>is defined
int max (int first, int second) {
return first > second? first : second;
}
Coroutines
• Acoroutineisasubprogramthathasmultipleentriesandcontrolsthem itself
• Alsocalledsymmetriccontrol:callerandcalledcoroutinesareonamore equalbasis
• A coroutine call is named aresume
• Thefirstresumeofacoroutineistoitsbeginning,butsubsequentcallsenter
atthepointjustafterthelastexecutedstatementinthecoroutine
• Coroutinesrepeatedlyresumeeachother,possiblyforever
• Coroutinesprovidequasi-concurrentexecutionofprogramunits(the
coroutines);theirexecutionisinterleaved,butnotoverlapped
• Asubprogramdefinitiondescribestheactionsrepresentedbythe subprogram
• Subprograms can be either functions orprocedures
• Localvariablesinsubprogramscanbestack-dynamicorstatic
• Threemodelsofparameterpassing:inmode,outmode,andinoutmode
• Some languages allow operatoroverloading
• Subprograms can begeneric
• A coroutine is a special subprogram with multipleentries
UNIT-VI
Abstract Data types
Topics
• Introduction to DataAbstraction
• LanguageExamples
• EncapsulationConstructs
• NamingEncapsulations
• Object-OrientedProgramming
• Implementation of Object-OrientedConstructs
• ConcurrencyIntroduction
• Introduction to Subprogram-LevelConcurrency
• Semaphores
• Monitors
• MessagePassing
• Ada Support forConcurrency
• JavaThreads
• C#Threads
• Statement-LevelConcurrency
Advantages of DataAbstraction
• Advantage of the firstcondition
–together),
Program organization, modifiability (everything associated with a data structure is
and separate compilation
• Advantage the secondcondition
–Reliability--by hiding the data representations, user code cannot directly
accessobjectsofthetypeordependontherepresentation,allowingthe
representationtobechangedwithoutaffectingusercode
Language Requirements for ADTs
• Asyntacticunitinwhichtoencapsulatethetypedefinition
• Amethodofmakingtypenamesandsubprogramheadersvisibletoclients, while hiding
actualdefinitions
• Someprimitiveoperationsmustbebuiltintothelanguageprocessor DesignIssues
• Can abstract types beparameterized?
• What access controls areprovided?
• Havingpartoftheimplementationdetails(therepresentation)inthespec
packageandpart(themethodbodies)inthebodypackageisnotgood
1. Difficulties withpointers
2. Objectcomparisons
3. Control of object allocation islost
–Necessary in C++
Language Examples:Java
• SimilartoC++,except:
–All user-defined types are classes
–Allobjectsareallocatedfromtheheapandaccessedthroughreference variables
Individualentitiesinclasseshaveaccesscontrolmodifiers(privateorpublic), rather thanclauses
–
Javahasasecondscopingmechanism,packagescope,whichcanbeusedin place offriends
–• Allentitiesinallclassesinapackagethatdonothaveaccesscontrol modifiers are visible
throughout thepackage
An Example in Java
class StackClass{
private:
private int [] *stackRef;
private int [] maxLen, topIndex;
publicStackClass(){//aconstructor
stackRef=new int[100];
maxLen = 99;
topPtr = -1;
};
public void push (int num) {…}; public
void pop () {…};
public int top () {…};
public boolean empty () {…};
}
Language Examples: C#
• Based on C++ andJava
• Adds two access modifiers, internal and protectedinternal
• All class instances are heapdynamic
• Default constructors are available for allclasses
• Garbagecollectionisusedformostheapobjects,sodestructorsarerarely used
• structsarelightweightclassesthatdonotsupportinheritance
C# Property Example
public class Weather {
publicintDegreeDays{//**DegreeDaysisaproperty get
{returndegreeDays;}
set {
if(value<0||value>30)
Console.WriteLine(
"Valueisoutofrange:{0}",value); else
degreeDays =value;}
}
private int degreeDays;
...
}
...
Weather w = new Weather();
int degreeDaysToday, oldDegreeDays;
...
w.DegreeDays = degreeDaysToday;
...
oldDegreeDays = w.DegreeDays;
stack stk(100);
Parameterized ADTs in C++ (continued)
• Thestackelementtypecanbeparameterizedbymakingtheclassa templatedclass
template<classType> class
stack{
private:
Type *stackPtr; const
int maxLen; int topPtr;
public:
stack() {
stackPtr = new Type[100];
maxLen = 99;
topPtr = -1;
}
…
}
• Everything is anobject
–Advantage - elegance and purity
–Disadvantage - slow operations on simple objects
• Add objects to a complete typingsystem
–Advantage - fast operations on simple objects
–Disadvantage - results in a confusing type system (two kinds of entities)
•Includeanimperative-styletypingsystemforprimitivesbutmakeeverything elseobjects
–Advantage-fastoperationsonsimpleobjectsandarelativelysmalltyping system
–Disadvantage - still some confusion because of the two type systems
Are Subclasses Subtypes?
• Doesan―is-a‖relationshipholdbetweenaparentclassobjectandanobject of thesubclass?
Ifaderivedclassis-aparentclass,thenobjectsofthederivedclassmust behave the same as the parent
–
classobject
• Aderivedclassisasubtypeifithasanis-arelationshipwithitsparentclass
–―compatible‖ways
Subclasscanonlyaddvariablesandmethodsandoverrideinherited methods in
–Can the new class be nested inside the class that uses it?
–Insomecases,thenewclassisnestedinsideasubprogramratherthan directly in anotherclass
• Otherissues:
–Whichfacilitiesofthenestingclassshouldbevisibletothenestedclassand viceversa
Support for OOP in Smalltalk
• Smalltalk is a pure OOPlanguage
–Everything is an object
–All objects have local memory
–All computation is through objects sending messages to objects
–None of the appearances of imperative languages
–Allobjectedareallocatedfromtheheap All
–deallocation isimplicit
Support for OOP in Smalltalk (continued)
• Type Checking andPolymorphism
–All binding of messages to methods is dynamic
• The process is to search the object to which the message is sent for the
method;ifnotfound,searchthesuperclass,etc.uptothesystemclasswhich has nosuperclass
TheonlytypecheckinginSmalltalkisdynamicandtheonlytypeerror
–
occurswhenamessageissenttoanobjectthathasnomatchingmethod
–Privatederivation-inheritedpublicandprotectedmembersareprivateinthe subclasses
Publicderivationpublicandprotectedmembersarealsopublicand protected insubclasses
–
Inheritance Example in C++ class
base_class{
private:
int a;
floatx;
protected: int
b; floaty;
public:
int c;
floatz;
};
classsubclass_3:privatebase_class{ base_class
::c;
…
}
Reexportation (continued)
• One motivation for using privatederivation
–publicmembers;aderivedclassaddssomenewmembers,butdoesnotwant
A class provides members that must be visible, so they are defined to be
•BecauseofitscloserelationshiptoC++,focusisonthedifferencesfromthat language
• GeneralCharacteristics
–All data are objects except the primitive types
–All primitive types have wrapper classes that store one data value
–All objects are heap-dynamic, are referenced through reference variables, and most are allocated
with new
–Aninterfacecanincludeonlymethoddeclarationsandnamedconstants, e.g.,
public interface Comparable {
public int comparedTo (Object b);
}
–Methodscanbefinal(cannotbeoverriden) Support
for OOP in Java(continued)
• DynamicBinding
–overriden,
InJava,allmessagesaredynamicallyboundtomethods,unlessthemethod is final (i.e., it cannot be
therefore dynamic binding serves no purpose)
Staticbindingisalsousedifthemethodsisstaticorprivatebothofwhich disallowoverriding
–
Support for OOP in Java (continued)
• Several varieties of nestedclasses
• Allarehiddenfromallclassesintheirpackage,exceptforthenestingclass
• Nested classes can beanonymous
• Alocalnestedclassisdefinedinamethodofitsnestingclass
–No access specifier is used
SupportforOOPinJava(continued)
• Evaluation
–Design decisions to support OOP are similar to C++
–No support for procedural programming
–No parentless classes
–Dynamicbindingisusedas―normal‖waytobindmethodcallstomethod definitions
–Usesinterfacestoprovideasimpleformofsupportformultipleinheritance Support for OOP inC#
• Generalcharacteristics
–Support for OOP similar to Java
–Includes both classes and structs
–Classes are similar to Java‘s classes
–structsarelesspowerfulstack-dynamicconstructs(e.g.,noinheritance) Support for OOP in
C#(continued)
• Inheritance
–Uses the syntax of C++ for defining classes
–Amethodinheritedfromparentclasscanbereplacedinthederivedclassby marking its definition
withnew
–Theparentclassversioncanstillbecalledexplicitlywiththeprefixbase: base.Draw()
Support for OOP in C#
• Dynamicbinding
–To allow dynamic binding of method calls tomethods:
• The base class method is markedvirtual
• Thecorrespondingmethodsinderivedclassesaremarkedoverride
–Abstractmethodsaremarkedabstractandmustbeimplementedinall subclasses
AllC#classesareultimatelyderivedfromasinglerootclass,Object Support for OOP in
–
C#(continued)
• NestedClasses
–AC#classthatisdirectlynestedinanestingclassbehaveslikeaJavastatic nestedclass
–C#doesnotsupportnestedclassesthatbehavelikethenon-staticclassesof
Java
Support for OOP in C#
• Evaluation
–C# is the most recently designed C-based OO language
–ThedifferencesbetweenC#‘sandJava‘ssupportforOOParerelativelyminor Support for OOP in
Ada95
• GeneralCharacteristics
–OOP was one of the most important extensions to Ada 83
–Encapsulation container is a package that defines a tagged type
–Ataggedtypeisoneinwhicheveryobjectincludesatagtoindicateduring execution its type (the
tags areinternal)
–Taggedtypescanbeeitherprivatetypesorrecords
–Noconstructorsordestructorsareimplicitlycalled
Support for OOP in Ada 95 (continued)
• Inheritance
–Subclasses can be derived from tagged types
–Newentitiesareaddedtotheinheritedentitiesbyplacingtheminarecord definition
–All subclasses are subtypes
–No support for multiple inheritance
• Acomparableeffectcanbeachievedusinggenericclasses Example of a
TaggedType
Package Person_Pkg is
type Person is tagged private;
procedureDisplay(P:inoutPerson); private
type Person is tagged record
Name : String(1..30); Address
: String(1..30); Age : Integer;
end record;
end Person_Pkg;
with Person_Pkg; use Person_Pkg;
package Student_Pkg is
typeStudentisnewPersonwith record
Grade_Point_Average : Float;
Grade_Level : Integer;
end record;
procedureDisplay(St:inStudent);
endStudent_Pkg;
–theCIR
Callstodynamicallyboundmethodscanbeconnectedtothecorresponding code thru a pointer in