Chapter 07
Upcoming SlideShare
Loading in...5
×
 

Chapter 07

on

  • 1,491 views

Robert W Sebesta

Robert W Sebesta
8th Edition
Chapter 07

Statistics

Views

Total Views
1,491
Views on SlideShare
1,491
Embed Views
0

Actions

Likes
0
Downloads
40
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • From Robert W Sebesta , Concept of Programming Languages , 8th Edition
  • Dividend , Divisor , Sign
  • We are not talking about the commutative propertyWe mean to say whether value of Expression1 or Expression 2 comes from Memory
  • Referential Transparency and Side effects
  • Due to exponent
  • Optimization + possible Bugs

Chapter 07 Chapter 07 Presentation Transcript

  • Chapter 07
    Arithmetic Expression , Overloaded Operators , Type Conversions , Relational and Boolean Expressions, Short Circuit Evaluation , Assignment Statements , Mixed Mode Assignments
    BY
    Abdul-Wahab
  • Issues of Imperative languages.
    Character , string matching expressions in CH 6.
  • Fundamental means of specifying computation.
    Syntax , BNF Form.
    Semantics , What do they mean? And evaluated.
  • Expression Evaluation
    Order of Operators and Operator Evaluation.
    Associatively and Precedence rules of PL
    Operand Evaluation is unstated and left on Implementers.
    Different Implementation results in different results.
    Other issues in Semantics are Type Mismatches , Coercion and Short Circuit Evaluation.
  • Assignment statements have dominant role in Imperative Languages.
    Purpose of Assignment Statement is to change the state of the variable.
    Non Imperative Languages e.g Functional Programming Languages use variable as parameters of Functions.
    Simple Assignment Statement
    Target := Expression
  • Arithmetic Expressions
    It all started with automatic Evaluation of arithmetic Expressions from First High level Languages.
    Most Conventions were taken from Mathematics.
    In PL , Operands , Operators , Parenthesis and function call are part of Arithmetic Expression.
  • Design issues of arithmetic expression
    What are the operator precedence rules.
    What are operator Associativity rules.
    What is the order of Operand Evaluation.
    Are there restrictions on Operand Evaluation Side effect.
    Does the Language Allow User-defined operator Overloading.
    What type mixing is allowed in expression.
  • Operator Evaluation Order
    Precedence
    Value on expression may depends on it.
    a + b * c
    Operator precedence rules from Mathematicians.
    Rules almost same for all Imperative languages.
    U.S => PEMDAS
    "Please Excuse My Dear Aunt Sally".
    It stands for "Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction".
  • Why Precedence of Operators
    Logic by Mathematicians
    Multiply is based on Addition
  • Unary version of Addition and Subtraction.
    Unary Addition is called Identity Operator.
    Input = output , no effect on Operand.
    Ellis and Storstroup named it as Historical mistake and useless operator.
    Java and C # has a effect , it coercively change short ,byte to int.
    C changes it to int type.
    A + ( - B ) * C is legal but
    A + - B * C usually is not (legal in C based language)
  • Precedence of Unary Operator
    -A / B
    -A * B
    -A ** B
    in Ruby ADA, FORTRAN and BASIC ( ** has high precedence)
    -A ** B
    Is Equivalent to
    - ( A ** B )
  • Unary and MOD
    In Ada , Mod has higher precedence than Unary.
    - 17 mod 5
    Is equivalent to
    (17 mod 5)
  • What is the difference between Mod and Rem ?
  • APL , has single level precedence for all operators .
  • Associativity
    a – b + c – d
    a + b - c
    When an expression contains two adjacent occurrences of operators with the same level of precedence , the question of which operator is evaluated first is answered by Associativity.
    Adjacent operators are separated by a single operand with same level of precedence.
  • Exponent Operator
    Usually from Left to Right
    Exponentiation is from Right to left (Ruby and FORTRAN)
    A ** B ** C
    In Ada ** is non Assosiative
    A ** B ** C is illegal
    Use of Parenthesis to do the job
    In Ada ** is non Assosiative
    In Visual Basic ^ is for exponentiation and is right associative.
  • Associative rules for imperative languages
  • Single Level Precedence of APL
    Total Dependency on Associativity
    Right to Left
    A X B + C
  • Associativity of Operators
    Addition , Multiplication mathematically Associative
    Subtraction and division is not
    A+B+C order doesn’t matter
    In Computers This doesn’t hold for floating point arithmetic
    A+ A –A -A
    A+A –B –B
    Suppose A and B are very large numbers
    Overflow problems and optimization ( C , C++ , ??)
  • Paranthesis
    Used to alter the precedence and Associativity.
    Advantage
    Readability and More control , No need to remember
    Not good for simple expression
    Demerit of not using Parenthesis
    Over complexities
  • Ruby Expressions
    Pure Object Oriented Programming
    Every data value , including literal is an object.
    Ruby supports collection of Arithmetic and Logical operation so C Based Language.
    But Every thing is implemented as method
    e.ga+b
    Overloading of predefined methods (Not recommended)
    But Useful in some cases
    Operator overloading for user defined types
  • Conditional Expressions
    Ternary Operator ?:
    If – then – else statement
    If (count == 0 )
    Average = 0;
    Else
    Average = sum / count;
    Expression_1 ? Expression_2 : expression_3
    Expression_1 is Boolean expression
    Average = (count ==0 ) ? 0 : sum/count
  • Operand Evaluation Order
    Expression OPERATOR Expression
    Variables in expression are evaluated by fetching their values from memory (Constant case may be different)
    If Expression is paranthesized then all its variables must be evaluated before it can be used as an operand
    If there is no side effect then the Operand Order is irrelevant
    Lets look at the Operand Evaluation which has side effects
  • Side Effect
    A side effect of a function called a functional side effect.
    A Function changing the global variable
    By use of Reference variable , Pass by Reference
    a + fun (a)
    a + fun(b)
    Void fun(){
    // assuming a is a global variable
    a
    }
  • Note :
    There are not functional side effects in Mathematics
    There are probably no side effects in pure functional Programming languages
    Because there context is irrelevant to its meaning
  • Two Possible Solutions to the Problem:
    1. Write the language definition to disallow functional side effects
    No two-way parameters in functions
    No non-local references in functions
    Advantage: it works!
    Disadvantage: Programmers want the flexibility of two-way parameters (what about C?) and non-local references
    2. Write the language definition to demand that operand evaluation order be fixed
    Disadvantage: limits some compiler optimizations
  • Java provides left to right operand evaluation.
    Ada let you specify the order
  • Overloaded Operators
    Arithmetic Operators are often used for more than one purpose.
    + , for integer and float addition , catenation
    This multiple use of operators is called Operator Overloading
    Operator Overloading ( Function Overloading )
  • It is acceptable , if readability and reliability is not compromised.
    & , Address , Bitwise AND , reference Operator.
    Deterimental to readability and reliabilty
    E.g x = z & y => x = &y
    Missing the z will go undetected by compiler.
  • Unary Minus operator (Less Serious)
    X = z – y => X = - y
    Distinct Operation not only increase readability but are sometimes convenient to use for common operation as well
    E.g division operator
  • Sum , count (int) , avg (float)
    avg = sum / count
    Integer division
    Soln:
    Separate Operator , ( / , div ) Pascal
    Inferencing on LHS , both operand will
    coercively converted to float
    Dynamic Language like php based on the result generate the type
    Java Script provides only float division.
  • FORTRAN , Ada , C++ , C # , allows the programmer to further overload operator symbol.
    e.g between scalar and integer array.
    could overload * whenever
    For int * int array
    And for Abstract User defined type . E.g Student.
  • Evaluation
    When Sensibly used could improve Readability
    For Matrix Operations
    A * B + C * D
    MatrixAdd( MatrixMult(A,B) , MatrixMult(C,D) )
    Demerits of Operator Overloading for UDTs
    Student1 < Student 2
  • Non Overloadable Operators
    E.g dot . , :: etc
    Not Taken by Java
    Taken by C Sharp
  • Type Conversions
    Narrowing Conversion
    Convert a value that cannot store all the approximation of original type
    Double to float ( much higher in java)
    Widening Conversion
    Consider as safe but not always
    Byte to integer
    Float to double
    Int to long
    Exception ( they may result in lost of accuracy)
    Int to float may loose accuracy upto 2 decimal points
  • Coercion in Expression
    Mix Mode Expression
    String + int
    Int is coerced to be a string
    Coercion is good or bad
    Programmer vs compiler
    Mix Mode expressions are legal in Java
    int a;
    float b , c , d;
    …..
    d = b * a; // simply coerced a to float
  • Ada , does not allow much Mix Mode Expression
    Exception is with the ( ** )Exponential operator.
    First operand integer/ float
    Second Operand integer
    Other exceptions of Mix Mode Expressions in Ada are with subtypes.
  • Byte , short in C based language
    When used with operator are coerced with int type.
    A = b + c
    Utilization of Memory is efficient
    Handy in large arrays
  • Explicit Type Conversion
    Both Narrowing and Widening
    In C based languages it is called Cast.
    When Narrowing conversion result in significant lose , a warning or error is produced.
    ( int ) angle
    Why use brackets (long int )
    Ada , Float (sum)
  • Errors in Expression
    Statically and dynamicaly type checking avoid these problems
    Limitations of computer arithmetic , mathematical arithmetic.
    Aritmetic overflow , underflow , divide by zero.
    Mathemitally disallowed doesn’t mean programmer will not attempt it.
    Solution:
    Exception handling in Chapter 14
  • Relational and Boolean Expressions
    Relational Expression
    Comparison Operator
    Value of Relational Operator is Boolean if provided.
    Simple for arithmetic VS complex for strings
    2 < 3 VS abdulvsahad
    Fortran 95 NE <>
    Ada /=
    SQL <>
    C-Based !=
  • Java script and PHP has two additional operators
    === and !==
    == is coercive while === is not
    “77” == 77 is true VS “77” === 77 is false
    Ruby
    == for coercive and eql ? For non coercive
    Relationa Operators always have low Precedence.
    A+1 < b * 2
  • Boolean Expression
    AND OR NOT Exclusive OR
    Mathematicaly AND and OR are of same precedence so in Ada
    But not in C , AND has higher precedence
    ARW -> RE -> BE
  • C has no Boolean type
    A > b > c
    Left assosiative
    A> b is evaluated first and 0 or 1 is returned
    There is never a comparison of b and c
    2<7<1
    2<7>1
  • Ruby , Perl
    { AND , OR , && , || }
    And , OR have same precedence
    Spelled version have lower precedence
    && has higher precedence than ||
  • Arithmetic and Non Arithmetic Operators of C Based Language and at least 14 different level of precedence.
    Richness of collection of oeprators and complexities of Expressions
    C , C++
    Readability prefer boolean over numeric
    Coz , numeric is a legal operand to Boolean Operator
  • Short Circuit Evaluation
    Non Strict Evaluation
    A Short circuit Evaluation of an expression is one in which the result is determined without evaluating all of the operands and/ or operators
    E.g (13 * a ) * ( b + c +d * e / 3 ) + (e**d)
    If a= 0 , then no need to evaluate others
    ( b + c +d * e / 3 ) + (e**d) * * ( a – b )
    If a-b == 0 then result is 1
    However This is quite difficult to detect at run time so never taken.
  • Boolean Expression
    ( a >= 0 ) && (b < 10)
    Second Expression is independent
    False AND ? Equals false
  • OR
    Side effect may occur on complete evaluation
    Program correctness depends on it.
    ( a > b) || ( (b++) / 3 )
    Order is sometimes not mentioned
    left or right
  • Ada provides and then or else
    to specify Shortcircuit Evaluation
    Index :=1
    while ( Index < count ) and then ( array[index] /= key)
    Loop:
    Index := index + 1;
    End loop
  • In C Based Language
    && and &
    || and |
    What are the issues with it ?
  • Assignment
    One of the central constructs in Imperative languages.
    Imperative languages are based on von neuman architecture.
    syntax
    <target_variable> <assignment_operator> <expression>
    Most PL use of = as a assignment operator
    ALGOL 60 introduced := and then Ada followed
    C may have embedded assignment statements in expression.
    Fortran and Ada , Assignment can appear as
    Standalone statement
    Single target variable
  • Conditional Targets
    Flag ? count1 : count2 = 0;
    Equivalent to
    if ( Flag )
    Count1 = 0;
    else
    Count 2 = 0;
  • Compound Assignment Operators
    a = a+b;
    a += b;
    Introduced by ALGOL 68
    Now in all Imperative languages
  • Unary Assignment Operators
    Count = count + 1
    Count ++;
    Preceede / follow the operand
    Sum = ++ count;
    Count = count + 1
    Sum = count
    Sum = count++;
    Sum = count
    Count = count + 1
    -count ++ ( when two unary operators to same operand , Association is right to left )
    (count ++) // like this
    Rather than
    ( - count )++ // not like this
  • Assignment as Expression
    In C Based Languages , Perl , Javascript
    Assignment statement generates a result
    Like a binary operator (but it effects its second operand)
    if( a= 2){ // true in C , C++ if ( 2 ){
    }
    else{
    }
    Languages which does support , Assignment Operator has less precedence than relational operators
    If ( ( a=b ) != c )
    Without paranthesis it would be If ( ( a= (b != c ) ) // b != c produce 0 or 1
  • Contn’d
    Side effect of Assignment in Expression
    Readability
    Reliability
    Multiple Assignment
    Sum = count = 0;
  • List Assignment
    Perl and ruby provide it
    ($first , $second , $ third) = (20,40,60);
    ($first , $second) = ($second , $first)
    In C Based anguages
    Int ar[20] = {1,2,3,4,5,6}
    What If # of variables on R.H.S and L.H.S are mismatched
    Less and greater cases on R.H.S
    Ruby has more Elaborate cases
  • Mix Mode Assignment
    In case of type mismatch , use coercion or not.
    Fortran , C , C++ and Perl use coercion for mixed mode assignment.
    Java and C # use coercion for widening conversion is ok and also in some narrowing cases as well e.g int to char if it is in range.
    Int can be float but not vice verca
    In All language coerced after RHS expression evaluation
    One alternative is to coerced all operands to type of LHS
    Ruby and Python types are associated with objects , so there are no mix mode assignment.
  • Summary
    Expressions consist of constants , variables , parenthesis , function calls and operators.
    Assignment statements include target variable , assignment operators and expressions.
    Semantics of an Expression is determined in large by the order of the evaluation of operators.
    The Associativity and precedence rules for operators in the expression of a language determine the order of Operator evaluation in those expresion
    Operand evaluation order is important in functional side effects are possible.
    Type Conversion can be widening or narrowing .
    Some narrowing conversion can produced erroneous results.
    Implicit Conversion or coercion in expressions are common, although they eliminate the error detection benefit of type checking , thus lowering reliability.
    Assignment statements have appeared in a wide variety of forms , including conditional targets , assigning operators and list assignments.
  • Practices
    Solve the Problem set given at the end of this chapter.
    Practice each topic in your Assigned language and favorite language.
    E.g Ruby , java etc
    References :
    Most material other than the text book is taken from Wikipedia.