Chapter 07


Published on

Robert W Sebesta
8th Edition
Chapter 07

Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • 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

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

      Clipping is a handy way to collect important slides you want to go back to later.