1 programming languages lecture 2. 2 control structures any mechanism that departs from...

48
1 Programming Languages Programming Languages Lecture 2 Lecture 2

Post on 19-Dec-2015

217 views

Category:

Documents


0 download

TRANSCRIPT

11

Programming LanguagesProgramming Languages

Lecture 2Lecture 2

22

Control StructuresControl Structures Any mechanism that departs from straight-line execution:Any mechanism that departs from straight-line execution:

Selection: Selection: if-statementsif-statements Multiway-selection: Multiway-selection: case statementscase statements Unbounded iteration: Unbounded iteration: while-loopswhile-loops Definite iteration: Definite iteration: for-loopsfor-loops Iterations over collectionsIterations over collections transfer of control: transfer of control: gotos gotos (considered harmful!)(considered harmful!) unbounded transfer of control: unbounded transfer of control: exceptions, backtrackingexceptions, backtracking

Characteristic of Imperative languagesCharacteristic of Imperative languages All you need for a universal machine: increment, All you need for a universal machine: increment,

decrement, branch on zero. All the rest is programmer decrement, branch on zero. All the rest is programmer convenience!convenience!

Not efficient on modern pipelined processorsNot efficient on modern pipelined processors

33

SelectionSelection ifif Condition Condition thenthen Statement Statement elseelse Statement Statement -- Pascal, Ada-- Pascal, Ada ifif ( (ConditionCondition)) Statement Statement elseelse Statement Statement -- C, C++ Java-- C, C++ Java

Selection Expression: Condition Selection Expression: Condition ?? Expression Expression : : Expression -- Expression -- CC Characteristic of functional languages Characteristic of functional languages

To avoid ambiguities, use end marker: To avoid ambiguities, use end marker: end ifend if, , fifi, or bracketing , or bracketing { { }}

To deal with several alternatives, use keyword or bracketing:To deal with several alternatives, use keyword or bracketing:--Ada--Ada /* C *//* C */ifif Condition Condition then then ifif (Condition) { (Condition) { Statements Statements}Statements Statements}elsifelsif Condition Condition then then else ifelse if (Condition) { (Condition) {

Statements Statements}Statements Statements}elseelse else else { {

Statements Statements}Statements Statements}end ifend if; ;

44

Statement GroupingStatement Grouping Pascal introduces Pascal introduces begin-endbegin-end pair to mark sequence pair to mark sequence C/C++/Java abbreviate keywords to { }C/C++/Java abbreviate keywords to { } Ada dispenses with brackets for sequences, because Ada dispenses with brackets for sequences, because

keywords for the enclosing control structure are sufficient:keywords for the enclosing control structure are sufficient: forfor J in 1 .. N J in 1 .. N looploop … … end loopend loop;;

More writing => more readableMore writing => more readable

The use of grouping in C++/Java is just syntactic traditionThe use of grouping in C++/Java is just syntactic tradition Another possibility (ABC, Python): Another possibility (ABC, Python): make indentation make indentation

significantsignificant Nesting groups of statementsNesting groups of statements

ifif Condition Condition thenthen ifif (Condition) (Condition)

if if Condition Condition thenthen ifif (Condition) { (Condition) { Statements Statements Statements Statements end ifend if; }; } else else elseelse { { Statements Statements Statements Statements end ifend if; ; }}

55

Short-Circuit EvaluationShort-Circuit Evaluation If x is more than five times greater than y, If x is more than five times greater than y,

compute z:compute z: ifif x / y > 5 x / y > 5 thenthen z := … z := … -- but what if y is 0?-- but what if y is 0? ifif y /= 0 y /= 0 andand x/ y > 5 x/ y > 5thenthen z := … z := … -- but operators evaluate -- but operators evaluate

their argumentstheir arguments

Solutions:Solutions: a lazy evaluation rule for logical operators (LISP, C, etc)a lazy evaluation rule for logical operators (LISP, C, etc) a control structure with a different syntaxa control structure with a different syntax

C1 && C2 C1 && C2 does not evaluate C2 if C1 is does not evaluate C2 if C1 is false false

ifif C1 C1 andand thenthen C2 C2 thenthen dittoditto C1 || C2 C1 || C2 does not evaluate C2 if C1 is does not evaluate C2 if C1 is

truetrue ifif C1 C1 or elseor else C2 C2 thenthen dittoditto

66

Multiway selectionMultiway selection Generalization of condition Generalization of condition ifif from boolean to any from boolean to any

discrete typediscrete type Can be simulated with a sequence of if-statements, but Can be simulated with a sequence of if-statements, but

logic can become obscured.logic can become obscured.

casecase (X) (X) isis -- any integer value (discrete but large)-- any integer value (discrete but large) whenwhen integer’first .. 0 integer’first .. 0 => Put_Line (“negative”);=> Put_Line (“negative”); whenwhen 1 1 => Put_Line (“unit”);=> Put_Line (“unit”); whenwhen 3 | 5 | 7 | 11 3 | 5 | 7 | 11 => Put_Line (“small prime”);=> Put_Line (“small prime”); whenwhen 2 | 4 | 6 | 8 | 10 2 | 4 | 6 | 8 | 10 => Put_Line (“small even”);=> Put_Line (“small even”); whenwhen 21 21 => Put_Line (“house wins”);=> Put_Line (“house wins”); whenwhen 12 .. 20 | 22 .. 99 12 .. 20 | 22 .. 99 => Put_Line (“manageable”);=> Put_Line (“manageable”); when otherswhen others => Put_Line (“Irrelevant”);=> Put_Line (“Irrelevant”); end caseend case;;

All choices must be computable at compile-timeAll choices must be computable at compile-time

77

The well-structured case The well-structured case statementstatement

Enforced in Enforced in CC AdaAdaType of expression must be discrete: an Type of expression must be discrete: an enumerable set of values (floating-point enumerable set of values (floating-point numbers not acceptable)numbers not acceptable)

YY YY

Each choice is independent of the others Each choice is independent of the others (no flow-through)(no flow-through)

NN YY

All possible choices are covered exactly All possible choices are covered exactly onceonce

NN YY

There is mechanism to specify a default There is mechanism to specify a default outcome for choices not given explicitly.outcome for choices not given explicitly.

YY YY

88

LoopsLoops Definite LoopsDefinite Loops

forfor J J inin Integer Integer rangerange 1 .. 10 1 .. 10 looploop statementsstatementsendend looploop;;

Indefinite LoopsIndefinite Loops whilewhile condition condition looploop

statementsstatementsend loopend loop;;

looploop statementsstatementsend loopend loop;;

All loops can be expressed as while-loops (e.g., in C)All loops can be expressed as while-loops (e.g., in C)forfor (i = 0; i <10; i++) … equivalent to: i=0; (i = 0; i <10; i++) … equivalent to: i=0; whilewhile (i<10) { … i++;} (i<10) { … i++;}

Condition is evaluated at each iterationCondition is evaluated at each iteration If condition is initially false, loop is never executedIf condition is initially false, loop is never executed whilewhile Condition Condition looploop .. .. end loopend loop;; equivalent toequivalent to ifif Condition Condition thenthen whilewhile Condition Condition looploop … … end loopend loop; ; end ifend if;;

99

What if we want to execute at What if we want to execute at least once?least once?

Pascal introduces Pascal introduces until-loopuntil-loop.. C/C++ use different syntax with C/C++ use different syntax with whilewhile::

whilewhile (Condition) { … } (Condition) { … }dodo { … } { … } whilewhile (Condition) (Condition)

Can always simulate with a boolean variable:Can always simulate with a boolean variable:done := done := FalseFalse;;whilewhile ( (not not done) done) looploop

… … ifif Condition Condition thenthen done := True; done := True;

end loopend loop;;

1010

Unstructured flow (Duff’s device)Unstructured flow (Duff’s device)voidvoid send (int* to, int* from, int count) { send (int* to, int* from, int count) { int n = (count + 7 ) / 8;int n = (count + 7 ) / 8; switchswitch (count % 8) { (count % 8) {

casecase 0 : 0 : dodo { *to++ = *from++; { *to++ = *from++;casecase 7 : *to++ = *from++; 7 : *to++ = *from++;casecase 6 : *to++ = *from++;6 : *to++ = *from++;casecase 5 : *to++ = *from++; 5 : *to++ = *from++;casecase 4 : *to++ = *from++; 4 : *to++ = *from++;casecase 3 : *to++ = *from++; 3 : *to++ = *from++;casecase 2 : *to++ = *from++; 2 : *to++ = *from++;casecase 1 : *to++ = *from++; 1 : *to++ = *from++;

} } whilewhile (--n >0);(--n >0);}}

What does this do? Why bother?What does this do? Why bother?

1111

Breaking outBreaking out

More common is the need for an indefinite loop More common is the need for an indefinite loop that terminates in the middle of an iteration.that terminates in the middle of an iteration.

C/C++/Java: C/C++/Java: breakbreak Break out of Break out of whilewhile, , dodo, , forfor, , switchswitch statements statements

Ada : Ada : exitexit statement statementlooploop -- infinite loop-- infinite loop compute_first_part;compute_first_part;

exit whenexit when got_it; got_it; compute_some_more;compute_some_more;

end loopend loop;;

1212

Breaking out of Nested Breaking out of Nested LoopsLoops

Within nested loops, useful to specify exit Within nested loops, useful to specify exit from several of themfrom several of them

Ada solution: give names to loopsAda solution: give names to loops Otherwise: use a counter (Modula) or use Otherwise: use a counter (Modula) or use

a goto.a goto.

Outer: Outer: whilewhile C1 C1 looploop ... ... Inner: Inner: whilewhile C2 C2 looploop...... Innermost: Innermost: whilewhile C3 loop... C3 loop... exitexit Outer Outer whenwhen Major_Failure; Major_Failure; exitexit Inner Inner whenwhen Small_Annoyance; Small_Annoyance; ...... end loopend loop Innermost; Innermost; end loopend loop Inner; Inner; end loopend loop Outer; Outer;

1313

Definite loopsDefinite loops Counting loops are iterators over discrete Counting loops are iterators over discrete

domains:domains: forfor J J inin 1..10 1..10 looploop … … forfor (int I = 0; I < N; I++ ) .. (int I = 0; I < N; I++ ) .. Design issues:Design issues:

Evaluation of bounds (only once, ever since Evaluation of bounds (only once, ever since Algol60)Algol60)

Scope of loop variableScope of loop variable Empty loopsEmpty loops Increments other than oneIncrements other than one Backwards iterationBackwards iteration non-numeric domainsnon-numeric domains

1414

The loop variableThe loop variable Best if local to loop and treated as constantBest if local to loop and treated as constant Avoids issue of value at termination, and Avoids issue of value at termination, and

value on abrupt exitvalue on abrupt exit

counter : integer := 17; counter : integer := 17; -- outer -- outer declarationdeclaration

...... forfor counter counter inin 1 ..10 1 ..10 looploop do_something; -- 1 <= counter <= 10do_something; -- 1 <= counter <= 10 end loopend loop;; … … -- counter is still 17-- counter is still 17

1515

Different incrementsDifferent increments

The universal Algol60 form:The universal Algol60 form: forfor J J fromfrom Exp1 Exp1 toto Exp2 Exp2 byby Exp3 Exp3 dodo……

Too rich for most cases. Exp3 is most often +1, -1.Too rich for most cases. Exp3 is most often +1, -1. What is meaning if Exp1 > Exp2 and Exp3 < 0 ?What is meaning if Exp1 > Exp2 and Exp3 < 0 ? In C/ C++ In C/ C++ forfor (int J = Exp1; J <= Exp2; J = J + Exp3) … (int J = Exp1; J <= Exp2; J = J + Exp3) … In Ada:In Ada: forfor J J inin 1 .. N 1 .. N looploop -- increment is +1-- increment is +1 forfor J J in reversein reverse 1 .. N 1 .. N looploop -- increment is -1-- increment is -1 Everything else can be programmed with while-loopEverything else can be programmed with while-loop

1616

Non-numeric domainsNon-numeric domains Ada form generalizes to discrete types:Ada form generalizes to discrete types:

forfor M M inin months months looploop … …

General pattern for other data-types:General pattern for other data-types:define iterator class with primitive operations: define iterator class with primitive operations:

hasNext(), next()hasNext(), next()

Iterator it = Collection.Iterator(); Iterator it = Collection.Iterator(); while (it.hasNext) {while (it.hasNext) { element = it.next();element = it.next(); … …}}

APL avoids the need for iterators by automatically APL avoids the need for iterators by automatically extending scalar operations over composite data typesextending scalar operations over composite data typesa a 1 2 3 1 2 3b b 3 2 1 3 2 11 + a is 2 3 41 + a is 2 3 4a + b is 4 4 4a + b is 4 4 4

1717

RecursionRecursion Example:Example:

int fib(int n) {int fib(int n) {return (n <= 1) ? 1 : fib(n-1) + fib(n-2);return (n <= 1) ? 1 : fib(n-1) + fib(n-2);

} } Tail Recursion – when function returns Tail Recursion – when function returns

immediately after recursive call – can be immediately after recursive call – can be automatically transformed into a loopautomatically transformed into a loop

List processing with recursionList processing with recursionint max(List<Integer> list) {int max(List<Integer> list) { if (list.isEmpty()) {if (list.isEmpty()) { return Integer.min(); return Integer.min(); } else {} else { if (list.first() > max(list.deleteHead) {if (list.first() > max(list.deleteHead) {

return list.first();return list.first(); } else {} else { return max(list.deleteHead();return max(list.deleteHead(); }}}}}}

1818

Assignment Assignment Assignment always produces a side effect Assignment always produces a side effect variable := expression;variable := expression;

lvaluelvalue := := rvalue rvalue lvalue lvalue (left hand value) must be an address or (left hand value) must be an address or

reference. e.g., x, x[i] reference. e.g., x, x[i] but not but not (x + 1)(x + 1) rvaluervalue (right hand value) is a value (right hand value) is a value Types must matchTypes must match

In Ada, assignment is a statementIn Ada, assignment is a statement In C, C++, and Java it is an expressionIn C, C++, and Java it is an expression Initialization vs. AssignmentInitialization vs. Assignment Combination AssignmentCombination Assignment

X = X + 1 -- a mathematical absurdityX = X + 1 -- a mathematical absurdity X += 1 -- simpler and clearer X += 1 -- simpler and clearer

1919

Precedence & AssociativityPrecedence & Associativity Most languages enforce standard Most languages enforce standard

mathematical rulesmathematical rules APL doesn’t. Evaluation is always right APL doesn’t. Evaluation is always right

to leftto left Same for SmalltalkSame for Smalltalk

C++ has 18 levels of precedenceC++ has 18 levels of precedence Even if you know them all, the next Even if you know them all, the next

maintenance programmer might notmaintenance programmer might not Use parentheses Use parentheses

2020

ContinuationsContinuations

A Continuation represents a point in A Continuation represents a point in the computation, including all of the the computation, including all of the state information at that pointstate information at that point

All control structures (function calls, All control structures (function calls, loops, if, exceptions, goto, etc.) can loops, if, exceptions, goto, etc.) can be described using continuations be described using continuations

Scheme supports continuations as 1Scheme supports continuations as 1stst class objectsclass objects

2121

An Introduction to AdaAn Introduction to Ada

2222

What’s ADA all aboutWhat’s ADA all about Designed by committee for DoD Designed by committee for DoD Key goals:Key goals:

ReadabilityReadability Strong typingStrong typing

Detection of errors at compile timeDetection of errors at compile time Programming in the Large – Packages Programming in the Large – Packages

EncapsulationEncapsulation Separate compilation Separate compilation Data AbstractionData Abstraction

Run-time Error Handling – Exceptions Run-time Error Handling – Exceptions Reliable multi-TaskingReliable multi-Tasking Generic Units – parameterized typesGeneric Units – parameterized types

Emphasis on Programming as a Human ActivityEmphasis on Programming as a Human Activity

2323

Hello, WorldHello, World

A simple Ada Program, hello.adaA simple Ada Program, hello.ada

withwith text_IO; text_IO;

procedureprocedure hello hello isis

useuse text_IO; text_IO;

beginbegin

put(“Hello, World”);put(“Hello, World”);

endend hello; hello;

2424

Basic Structure of an ADA Basic Structure of an ADA ProgramProgram

Program UnitsProgram Units Packages, subprograms and tasksPackages, subprograms and tasks

SubprogramsSubprograms Procedures (do not return a value)Procedures (do not return a value) Functions (return a value)Functions (return a value)

PackagesPackages Collection of related data typesCollection of related data types

functions and proceduresfunctions and procedures Provides services to clientsProvides services to clients May use services of other packagesMay use services of other packages Defined in two partsDefined in two parts

Package Specification (.ads, .spc)Package Specification (.ads, .spc) Package BodyPackage Body (.adb, .bdy)(.adb, .bdy)

2525

Package Specification Package Specification Contain DeclarationsContain Declarations packagepackage X X isis

declarationsdeclarations types types subprogram specs subprogram specs (but not subprogram bodies) (but not subprogram bodies)endend X; X;

Specification provides public interface for Specification provides public interface for users of the package, but no users of the package, but no implementation detailsimplementation details

Specification is like a contract between the Specification is like a contract between the package and its clientspackage and its clients

2626

Subprogram SpecificationSubprogram Specificationprocedureprocedure Print_In_Hex (X : Integer); Print_In_Hex (X : Integer);functionfunction Max (A, B : Integer) Max (A, B : Integer) returnreturn Integer; Integer;

Similar to signatures in C and C++ header Similar to signatures in C and C++ header files.files. Headers can be generated automatically from the Headers can be generated automatically from the

source codesource code Java does this automatically with Java does this automatically with importimport statement statement

A subprogram spec has everything you need A subprogram spec has everything you need to know to use the subprogramto know to use the subprogram

A client sees only the specificationA client sees only the specification Implementation details are hiddenImplementation details are hidden Implementation can be changed without affecting Implementation can be changed without affecting

clientsclients

2727

Procedure BodyProcedure Body

procedureprocedure H (M : Integer) H (M : Integer) isis declarationsdeclarationsbeginbegin statementsstatements returnreturn;;endend H; H;

Typical use is procedure Main is …Typical use is procedure Main is …which defines the main program which defines the main program

File name must match main procedure nameFile name must match main procedure name

2828

Function BodyFunction Body

functionfunction Max (A : Integer; B : Integer) Max (A : Integer; B : Integer) returnreturn Integer Integerisis Result : Integer; Result : Integer;beginbegin ifif A > B A > B thenthen Result := A; Result := A; elseelse Result := B; Result := B; end ifend if;; returnreturn Result; Result;endend Max; Max;

2929

Package Bodies Package Bodies

Contain DefinitionsContain Definitions packagepackage bodybody X X isis

declarationsdeclarations subprograms local to body subprograms local to body variables/constants local to body variables/constants local to body subprogram bodies for subprogram subprogram bodies for subprogram specs appearing in the package spec specs appearing in the package specbeginbegin initialization statementsinitialization statementsendend X; X;

3030

How to be a Client of a How to be a Client of a packagepackage

To access a package, use To access a package, use WithWith andand UseUse statements:statements:

withwith Calendar, Text_IO; Calendar, Text_IO;useuse Text_IO;Text_IO;procedureprocedure Main Main isis Today : Calendar.Time; Today : Calendar.Time; put(“Today is” ); put(“Today is” );……

endend Main; Main; UseUse eliminates the need to specify the eliminates the need to specify the

package name, as in Calendar.Time, when package name, as in Calendar.Time, when using a package memberusing a package member

3131

Package ClientsPackage Clients Package BodiesPackage Bodies

withwith Calendar; Calendar;package package bodybody Julian_Calendar_Stuff Julian_Calendar_Stuff isis … …endend Julian_Calendar_Stuff; Julian_Calendar_Stuff;

Package implemented using another packagePackage implemented using another package Package SpecificationsPackage Specifications

withwith Calendar; Calendar;useuse Calendar; Calendar;packagepackage To_Do_List To_Do_List isis … … procedureprocedure Enter (T : Time; M : String); Enter (T : Time; M : String); -- Enter new item in todo list. Time is -- Enter new item in todo list. Time is -- deadline. M is description. -- deadline. M is description.endend To_Do_List; To_Do_List;

Package To_Do_List extends Calendar interfacePackage To_Do_List extends Calendar interface

3232

Using AdaUsing Ada Write your program using any text editorWrite your program using any text editor

Save it in a file named Save it in a file named myprogmyprog.adb, where .adb, where myprogmyprog is the is the name of the main procedure in the program.name of the main procedure in the program.

Compile your program:Compile your program:gnat make gnat make myprogmyprog.adb.adb On windows this produces a file On windows this produces a file myprogmyprog.exe, which you .exe, which you

can executecan execute On Unix you will have to make the file executable using On Unix you will have to make the file executable using

chmod a+x chmod a+x myprogmyprog Ada resources on the Web:Ada resources on the Web:

http://www.adapower.comhttp://www.adapower.com http://www.adahome.comhttp://www.adahome.com ftp://ftp://cs.nyu.educs.nyu.edu/pub/gnat/pub/gnat

3333

Writing an ADA ProgramWriting an ADA Program

Write the package specificationsWrite the package specifications Verify that specification is usable by Verify that specification is usable by

intended clientsintended clients Write the bodyWrite the body Write the clientsWrite the clients Last two activities are completely Last two activities are completely

independent (and should not talk to independent (and should not talk to one another except “via” the spec)one another except “via” the spec)

3434

Ada OperatorsAda OperatorsLogical Operators:Logical Operators: and or xorand or xorRelational Operators: Relational Operators: = /= < <= > >== /= < <= > >=Additive Operators:Additive Operators: + – &+ – &

& & is concatenation on vectors and stringsis concatenation on vectors and strings

Unary Operators:Unary Operators: + – not+ – notMultiplicative Operators: Multiplicative Operators: * / mod rem* / mod remExponentiation Operator: Exponentiation Operator: ****

3535

Integer TypesInteger Types Type Integer is built in – Type Integer is built in – But you don’t want to But you don’t want to

use it!use it! In ADA types are defined according to useIn ADA types are defined according to use

typetype Day_In_Year Day_In_Year is rangeis range 1 .. 366; 1 .. 366;typetype Age Age is rangeis range 0 .. 130; 0 .. 130;typetype Temperature Temperature is rangeis range -20 .. +180; -20 .. +180;

Now we can define variables of the typeNow we can define variables of the typeToday_Day : Day_In_Year;Today_Day : Day_In_Year;Employee_Age : Age;Employee_Age : Age;Machine_Room_Temp : Temperature;Machine_Room_Temp : Temperature;

Type AttributesType Attributes Integer’last, Year’lastInteger’last, Year’last Integer’first, Age’firstInteger’first, Age’first for A in Age’first … Age’last loopfor A in Age’first … Age’last loop

3636

Strong TypingStrong Typing No dependence on implementation -- Unlike type No dependence on implementation -- Unlike type

int in Cint in C Range of types matches problemRange of types matches problem

Get an error or warning at compile timeGet an error or warning at compile time Age := 200;Age := 200;

Or an exception at runtimeOr an exception at runtime Age := Age + 1000;Age := Age + 1000;

Cannot mix integer types:Cannot mix integer types:Current_Temp : Temperature; OK Current_Temp : Temperature; OK Current_Pressure : Pressure; OKCurrent_Pressure : Pressure; OKCurrent_Temp := Current_Pressure + 1; ErrorCurrent_Temp := Current_Pressure + 1; ErrorCurrent_Temp := Current_Temp + Current_Pressure; ErrorCurrent_Temp := Current_Temp + Current_Pressure; Error

Type Errors detected at Compile TimeType Errors detected at Compile Time

3737

Integer SubtypesInteger Subtypes

A subtype creates a limited rangeA subtype creates a limited range But is still the same typeBut is still the same type

subtypesubtype OK_Operating_Range OK_Operating_Range isis Temperature Temperature rangerange 70 .. 80; 70 .. 80;Room_Temp : Temperature;Room_Temp : Temperature;Machine_Room_Temp : Machine_Room_Temp : OK_Operating_RangeOK_Operating_Range……Machine_Room_Temp := Room_Temp;Machine_Room_Temp := Room_Temp;

Raises exception if Room_Temp out of rangeRaises exception if Room_Temp out of range

3838

Enumeration TypesEnumeration Types An enumeration type is a sequence of An enumeration type is a sequence of

ordered enumeration literals:ordered enumeration literals: TypeType State State isis (Off, Powering_Up, On); (Off, Powering_Up, On); TypeType Color Color isis (Red, Orange, Yellow, Blue, Green); (Red, Orange, Yellow, Blue, Green);

Not integers (as in C++)Not integers (as in C++)S1, S2 : State;S1, S2 : State;S1 := S1 + 1; – Error, butS1 := S1 + 1; – Error, butState’Pred (On) – OK, Powering_UpState’Pred (On) – OK, Powering_UpState’Succ (On) – OK, but raises State’Succ (On) – OK, but raises constraint_errorconstraint_error

Predefined enumeration typePredefined enumeration type typetype Boolean Boolean isis (False, True); (False, True);

Other Attributes include:Other Attributes include:T’First, T’Last, T’Val(n) where n is a value in TT’First, T’Last, T’Val(n) where n is a value in T

3939

Character TypesCharacter Types

Built in typesBuilt in types Character (8-bit Latin-1)Character (8-bit Latin-1) Wide_Character (16-bit Unicode/ISO Wide_Character (16-bit Unicode/ISO

10646)10646) Good enough for most purposes, but Good enough for most purposes, but

you can define your own types:you can define your own types: typetype My_Character My_Character isis (‘A’, ‘B’, ‘C’, ….); (‘A’, ‘B’, ‘C’, ….);

4040

String TypesString Types

A string type is an array whose A string type is an array whose elements are a character type.elements are a character type.

Two standard built in string typesTwo standard built in string types typetype String String is arrayis array

(Natural (Natural rangerange <>) of <>) of CharacterCharacter;;typetype Wide_String Wide_String is arrayis array (Natural (Natural rangerange <>) of <>) of Wide_CharacterWide_Character;;S : String (1 .. 5) := “Hello”;S : String (1 .. 5) := “Hello”;

Note: Natural is a predefined subtype of Note: Natural is a predefined subtype of Integer with bounds 0 .. Integer’Last;Integer with bounds 0 .. Integer’Last;

4141

Array TypesArray Types

Arrays can have 1 or more subscriptsArrays can have 1 or more subscripts typetype Vector Vector isis

arrayarray (Integer (Integer rangerange 1 .. 10) 1 .. 10) ofof Integer; Integer;typetype Matrix Matrix isis arrayarray (Integer (Integer rangerange 0 .. 10, 0 .. 10, Character Character rangerange ‘A’ .. ‘Z’) ‘A’ .. ‘Z’) ofof Vector; Vector;

VV : Vector; VV : Vector; MM : Matrix;MM : Matrix;……MM (5, ‘C’) := VV;MM (5, ‘C’) := VV;

4242

Array AttributesArray Attributes

A’First(N), A’Last(N), A’Length(N), A’First(N), A’Last(N), A’Length(N), A’Range(N)A’Range(N) N is the attribute for the Nth indexN is the attribute for the Nth index N must be staticN must be static Without a parameter, attributes refer to Without a parameter, attributes refer to

the first index - A’First, etc.the first index - A’First, etc. We can use the array range in loops We can use the array range in loops

forfor x x inin A’Range A’Range looploop result := result + A[x];result := result + A[x];

end loopend loop;;

4343

Unconstrained ArraysUnconstrained Arrays

Unconstrained array type has no Unconstrained array type has no boundsbounds typetype UA UA is arrayis array (Int range <>) (Int range <>) ofof Int; Int;

-- cannot use UA to declare a variable-- cannot use UA to declare a variable-- instead must build a subtype-- instead must build a subtypesubtypesubtype UA5 UA5 isis UA (1 .. 5); UA (1 .. 5);UAV5 : UA5 := (6,5,4,3,2);UAV5 : UA5 := (6,5,4,3,2);-- can also set bounds for a variable-- can also set bounds for a variableUAV2 : UA (1 .. 2);UAV2 : UA (1 .. 2);

4444

Access TypesAccess Types Access types function like pointersAccess types function like pointers

But are not necessarily implemented that wayBut are not necessarily implemented that way typetype r r is accessis access integer; integer;

Allocate an object using Allocate an object using newnew typetype AI AI is access all is access all integer;integer;

Ptr : AI;Ptr : AI;……Ptr := Ptr := newnew Integer; Integer; -- uninitialized-- uninitializedPtr := Ptr := newnew Integer’(12); Integer’(12); -- initialized-- initialized

To obtain value dereference:To obtain value dereference: V : Integer;V : Integer;

……V := Ptr.V := Ptr.allall;;

4545

Declaring and Handling Declaring and Handling ExceptionsExceptions

Declaring an exceptionDeclaring an exception Error, Disaster : Error, Disaster : exceptionexception;;

Raising an exceptionRaising an exception raiseraise Disaster; Disaster;

-- strips stack frames till a handler is found-- strips stack frames till a handler is found Handling an exceptionHandling an exception

exceptionexception whenwhen Disaster => Disaster => statementsstatements

4646

Catching ExceptionsCatching Exceptions

You can catch an exception at run timeYou can catch an exception at run time beginbegin

… … Machine_Room_Temp := Room_Temp Machine_Room_Temp := Room_Temp

… …exceptionexception whenwhen Constraint_Error => Constraint_Error => recovery stuffrecovery stuff whenwhen Meltdown_Error => Meltdown_Error => recovery stuffrecovery stuff

… …endend;;

4747

Block StatementBlock Statement

Block statement can be used anywhereBlock statement can be used anywhere declaredeclare -- declare section optional -- declare section optional

declarationsdeclarationsbeginbegin statementsstatementsexceptionexception -- exception section -- exception section optionaloptional handlershandlersendend;;

4848

Access TypesAccess Types Access types function like pointersAccess types function like pointers

But are not necessarily implemented that wayBut are not necessarily implemented that way typetype r r is accessis access integer; integer;

Allocate an object using Allocate an object using newnew type type AI AI is access allis access all integer; integer;

Ptr : AI;Ptr : AI;……Ptr := Ptr := newnew Integer; Integer; -- uninitialized-- uninitializedPtr := Ptr := newnew Integer’(12); Integer’(12); -- initialized-- initialized

To obtain value dereference:To obtain value dereference: V : Integer;V : Integer;

……V := Ptr.V := Ptr.allall; ;