3. Fundamental means of specifying computation. Syntax , BNF Form. Semantics , What do they mean? And evaluated.
4. 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.
5. 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
6. 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.
7. 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.
8. 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".
9. Why Precedence of Operators Logic by Mathematicians Multiply is based on Addition
10. 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)
11. 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 )
12. Unary and MOD In Ada , Mod has higher precedence than Unary. - 17 mod 5 Is equivalent to (17 mod 5)
14. APL , has single level precedence for all operators .
15. 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.
16. 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.
19. 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++ , ??)
20. 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
21. 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
22. 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
23. 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
24. 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 }
25. 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
26. 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
27. Java provides left to right operand evaluation. Ada let you specify the order
28. 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 )
29. 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.
30. 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
31. 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.
32. 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.
33. 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
35. 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
36. 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
37. 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.
38. 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
39. 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)
40. 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
41. 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 !=
42. 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
43. 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
44. 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
45. Ruby , Perl { AND , OR , && , || } And , OR have same precedence Spelled version have lower precedence && has higher precedence than ||
46. 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
47. 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.
48. Boolean Expression ( a >= 0 ) && (b < 10) Second Expression is independent False AND ? Equals false
49. 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
50. 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
51. In C Based Language && and & || and | What are the issues with it ?
52. 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
53. Conditional Targets Flag ? count1 : count2 = 0; Equivalent to if ( Flag ) Count1 = 0; else Count 2 = 0;
55. 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
56. 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
57. Contn’d Side effect of Assignment in Expression Readability Reliability Multiple Assignment Sum = count = 0;
58. 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
59. 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.
60. 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.
61. 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.
Hinweis der Redaktion
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