Imperative Programming

Embed Size (px)


Imperative Programming. Imperative Programming. Most widely used paradigm Oldest paradigm Largest number of languages E.g. C, FORTRAN, Java/C++ (without the objects) Features closely related to machine architecture Based on the von Neumann stored program model - PowerPoint PPT Presentation

Text of Imperative Programming

  • Imperative Programming

  • Imperative Programming

    Most widely used paradigmOldest paradigmLargest number of languagesE.g. C, FORTRAN, Java/C++ (without the objects)Features closely related to machine architecture Based on the von Neumann stored program modelWe will skip a number of topics in this chapter as you should already be familiar with them from previous courses

  • Imperative ProgrammingLanguage StructureDeclarationsAssociate variables with memory locationsExpressionsEvaluated in the current environmentCommandsExecution and flow of controlSimilar to the machine instructionsAssignmentDynamically updates data storeConditionalsStatements executed or skippedBranching Alters the flow of controlSupports loopingBasis for defining an effective programming language

  • Turing CompletenessA programming language is said to be Turing Complete if it containsInteger variables, values and operationsAssignments, branching, sequencing, and conditionalsOther features make languages easier to program for complex applicationsLoopsProceduresObject OrientationBut they have the same power as any other programming languagei.e. what is possible to compute in one is possible in the otherJay is Turing Complete

  • Other Features Typical Turing complete language today supports:Data types for reals, chars, strings, booleansFor, while, switchArraysRecordsI/O commandsPointersProcedures and functions

  • Imperative Programming Design PrinciplesStructured Programming The structure of the program text should be the guide to understanding what it does.Can be more efficientImproved readabilityEasier to tune and modifyEfficiencyA language must allow an underlying assignment-oriented machine to be used directly and efficiently.Driving factor in the implementation of many imperative languages

  • Types in Typical Imperative LanguagesEmphasis on data structures with assignable componentsBased on values that can be manipulated directly by underlying machineSize and layout fixed at compile timeStorage allocated and deallocated explicitlyStrongly typedStorage efficiency is the key

  • Naming and VariablesSkipping in TextReserved wordsVariables uniqueConcept of scope, scoping rules

  • Types, Values and Expressions in JayLets look at defining types, values, and expressions in JayJay supports only two typesBoolean and IntegerBooleanValues: {true,false}Operations: &&, ||, !IntegerValues: {,-2,-1,0,1,2,..}OperationsArithmetic : +,-,*,/Relational: ==, !=,

  • Expressions in JayExpression has the formsValueVariableResult of a binary operationResult of a unary operationType of an expression is defined by the types of its constituentsConstituentExpression TypeValueType of the valueVariableType of the variableArithmetic Binary operator intRelational Binary operator booleanUnary operatorboolean

  • Formally Defining TypesBack to the typemap format from chapter 3:

  • Types of ExpressionsFormally defining expression types in Jay:

  • Jay Expression ExampleDeclaration: int x,y;Expressions: x+2*y x
  • Validity of ExpressionstypeOf function determines the type of expressionstypeOf function does NOT determine the validity of the expressionNeed to check separately

  • Validity of ExpressionsAn expression is valid if it is:int or boolean ValueVariable in the type mapUnary with a UnaryOp operator and a valid boolean operandBinary with ArithmeticOp with two valid int operandsBinary with RelationalOp with two valid int operandsBinary with BooleanOp with two valid boolean operands

  • Formal Validity of ExpressionsMore formally:

  • Validity of Expressions

  • Expression ExampleValidity of x+2*yNote recursive nature of V

  • Expression Example

  • Semantics of JaySemantic domains Integers (I)Boolean (B)Meaning of a Jay Expression can be defined functionally:

    ApplyBinary : Computes a value given a binary operator and two operandsApplyUnary : Computes a value given a unary operator and one operandUses the properties of the underlying semantic domains

  • ApplyBinary Function

  • ApplyBinary, Cont.

  • Semantics ExampleMeaning of expression x+2*yNote recursive definitions

  • SemanticsApplyBinary depends on the meaning of the semantic domain of I and BSometimes it is possible to define the meanings directly without using domains, e.g. for the definitions of && and || without using and Using the Short Circuit evaluation method

  • Elementary Data TypesSkipping from bookNibble, byte, word, quadword, etc.IEEE 754 number formatUnicodeOperator overloading, type conversion (e.g. int/float)See textbook for similarity in C++ and Java operatorsBook uses ?: for conditionalE.g. x = (y>0) ? 1 : 2; If (y>0) x=1; else y=2;

  • Syntax and Semantics of JayRecall the following concrete and abstract syntax for Jay statements

    We can define validity for statements:

  • Semantics of SkipSkipSkip statement cant change the state

  • Semantics of AssignmentDiscussed in chapter 3

    For x=a+b

  • Semantics of ConditionalIf (a>b) max=a; else max=b

  • Conditional, continued

  • Semantics of BlockBlock is just a sequence of statements

    Example for Block b:fact = fact * i;i = i 1;

  • Block exampleb1 = fact = fact * i;b2 = i = i 1;M(b,) = M(b2,M(b1,))= M(i=i-1,M(fact=fact*i,))= M(i=i-1,M(fact=fact*i,{,}))=M(i=i-1,{,})={,}b

  • Semantics of LoopLoop = Expression test; Statement body

    Recursive definition

  • Loop ExampleInitial state ={}

    fact=1;i=N;while (i>1) {fact = fact * i;i = i -1;}After first two statements, = {,,}

  • Loop Example = {,,}M(while(i>1) {}, ) = M(while(i>1) {}, M(fact=fact*i; i=i-1;, )= M(while(i>1) {}, {,,})= M(while(i>1) {}, {,,})= M()={,,}

  • Syntax and Semantics for Real LanguagesFor LoopConcrete SyntaxForStatement for (Assign1opt; Expropt; Assign2opt) StatementAbstract SyntaxIdentical to Abstract Syntax for WhileSee text for detailsDo statementsConcrete SyntaxDoStatement do Statement while (Expression)Abstract SyntaxIdentical to Abstract Syntax for WhileDifferent semantics, must make sure body is execute once

  • Syntax and Semantics of Real LanguagesSwitch statementMulti-way IF statementSee book for details, straightforward extensionBreak/Continue statementBreak terminates switch or whileContinue terminates current iteration of while and jumps back to the loop testSemantics must be specified in definitions for switch and whileE.g. break statement in a switch:Meaning if no break is Meaning of first matching true statement and all subsequent statementsMeaning if break is Meaning of first matching true statement, all subsequent statements until one contains a break

  • ScopingSkipping scope, visibility, and lifetimeShould be familiar with this from JavaStatic scope Scope computed at compile timeDynamic scopeScope compute at run time

  • Extension to MethodsSuppose we would like to extend Jay to include methods (functions)Must augment the concrete syntax:

  • Sample Program

  • Syntax for MethodsMust modify BNF rules for statements to allow method calls as a statement or a factor within an expression:

  • Abstract Syntax for MethodsUnderlined rules indicate changes

  • Static Type Checking for MethodsNew validity rules now need to be added:Every method and global variable must have a unique IDAll local variables and parameters within a method must be unique with valid typesAll statements and expressions within the body of each method must be valid with respect to the variables and parameters accessible to themA return appears in every method with a nonvoid Type, and the type of the Expression in the return must be identical with the methods TypeEvery call has a name identical with the name of a method in the program and has the same number of arguments as the methodEvery argument in a call has the same type as the type given in the corresponding parameter in the method of that nameSee book for denotational semantics to implement these rules