Presentation is loading. Please wait.

Presentation is loading. Please wait.

9/14/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 05 Components of Programming Languages, Part II Reference: R.Sebesta,

Similar presentations


Presentation on theme: "9/14/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 05 Components of Programming Languages, Part II Reference: R.Sebesta,"— Presentation transcript:

1 9/14/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 05 Components of Programming Languages, Part II Reference: R.Sebesta, Chapter 7

2 9/14/2015Assoc. Prof. Stoyan Bonev2 Lecture Contents: Expressions Operands within Expressions Operators within Expressions The Assignment Operator The Assignment Statement

3 9/14/2015Assoc. Prof. Stoyan Bonev3 Expressions Expressions are defined as entities composed to contain operands and operators that specify some computation.

4 9/14/2015Assoc. Prof. Stoyan Bonev4 Expressions - Operands Typical operands: Literals: 34, 5.68, -.567

5 9/14/2015Assoc. Prof. Stoyan Bonev5 Expressions - Operands Typical operands: Literals: 34, 5.68, -.567 Named constants: PI, MAX, MIN, M –#define PI 3.14159265 //C,C++ –const int MAX = 100; //C,C++,C# –final int MIN = 0; //Java –Const M As Integer = 55 ‘VBasic

6 9/14/2015Assoc. Prof. Stoyan Bonev6 Expressions - Operands Typical operands: Constants: 34, 5.68, -.567 Named constants: PI, MAX, MIN, M Variables: price, value, tax[I] –Regular /scalar/ or Indexed /subscripted/

7 9/14/2015Assoc. Prof. Stoyan Bonev7 Expressions - Operands Typical operands: Constants: 34, 5.68, -.567 Named constants: PI, MAX, MIN, M Variables: price, value, tax[I] Struct members: Ann.age,Ann.name –struct Person { int age; string name; …}; –Person Ann;

8 9/14/2015Assoc. Prof. Stoyan Bonev8 Expressions - Operands Typical operands: Constants: 34, 5.68, -.567 Named constants: PI, MAX, MIN, M Variables: price, value, tax[I] Struct members: Ann.age,Ann.name Function Calls: sqrt(2.),fabs(a+b)

9 9/14/2015Assoc. Prof. Stoyan Bonev9 Expressions - Operands Typical operands: Constants: 34, 5.68, -.567 Named constants: PI, MAX, MIN, M Variables: price, value, tax[I] Struct members: Ann.age, Ann.name Function Calls: sqrt(2.), abs(a+b) Parenthesized Sub Expressions: (a+b)*c, b*(c-d+e%f)

10 9/14/2015Assoc. Prof. Stoyan Bonev10 Expressions - Operators Formal characteristics of operators: Precedence;

11 9/14/2015Assoc. Prof. Stoyan Bonev11 Expressions - Operators Formal characteristics of operators: Precedence; Associativity;

12 9/14/2015Assoc. Prof. Stoyan Bonev12 Expressions - Operators Formal characteristics of operators: Precedence; Associativity; Number of operands: –Unary – a sole operand –Binary – two operands –Ternary – three operands

13 9/14/2015Assoc. Prof. Stoyan Bonev13 Expressions - Operators Formal characteristics of operators: Precedence; Associativity; Number of operands: –Unary – a single operand –Binary – two operands –Ternary – three operands Infix, Prefix and Postfix operators; Precedence, associativity for C/C++ operators (see table on next slide).

14 9/14/2015Assoc. Prof. Stoyan Bonev14 NoNo OperatorAssociativity 1( )[ ]–>. L→R 2!~++––+– *&(type) sizeof R→L 3*/%*/%L→R 4+–+– 5 >L→R 6 >=L→R 7==!=L→R 8& 9^ 10|L→R 11&&L→R 12||L→R 13? :L→R 14=+=–=*=/=%= &=|= >= R→L 15,L→R

15 9/14/2015Assoc. Prof. Stoyan Bonev15 Expressions – Syntax Intro to BNF Intro to Backus Naur Form Intro to Backus Normal Form

16 9/14/2015Assoc. Prof. Stoyan Bonev16 Expressions – Syntax Syntax describes the expressions structure. How? Using BNF BNF /Backus Naur/Normal Form/ is a formalism to present syntax. See introductory example on next slides. Comprehensive survey on syntax of Programming Languages is presented in COS301 Compiler Theory course.

17 9/14/2015Assoc. Prof. Stoyan Bonev17 Expressions – Syntax Do you remember the Reg EXP concept to describe integer/real literals (operands of expressions)

18 9/14/2015Assoc. Prof. Stoyan Bonev18 Expressions – Syntax Do you remember the Reg EXP concept to describe integer/real literals (operands of expressions) D+ D+.D* | D*.D+

19 9/14/2015Assoc. Prof. Stoyan Bonev19 Expressions – Syntax Do you remember the Reg EXP concept to describe names/identifiers of variables (operands of expressions)

20 9/14/2015Assoc. Prof. Stoyan Bonev20 Expressions – Syntax Do you remember the Reg EXP concept to describe names/identifiers of variables (operands of expressions) L.(L|D)*

21 9/14/2015Assoc. Prof. Stoyan Bonev21 Expressions – Syntax Reg EXP are tool to describe separate entities or unique lexical units as literals or names Reg EXP are not the only possible tool to describe lexems Even more Reg EXP can not describe more complex program segments as combinations of names, literals and operators, i.e. expressions. There exists more powerful tool for this purpose – the grammar

22 9/14/2015Assoc. Prof. Stoyan Bonev22 Expressions – Syntax Reg EXP and grammar to describe integer literal RE = D+ Grammar: ::= | ::= 0 | 1 | 2 | … | 8 | 9

23 9/14/2015Assoc. Prof. Stoyan Bonev23 Expressions – Syntax Reg EXP and grammar to describe integer literal RE = D+ Grammar: C -> D | C D D -> 0 | 1 | 2 | … | 8 | 9

24 9/14/2015Assoc. Prof. Stoyan Bonev24 Expressions – Syntax Reg EXP and grammar to describe name RE = L.(L|D)* Grammar: ::= | | ::= a | b | … | Z ::= 0 | 1 | 2 | … | 8 | 9

25 9/14/2015Assoc. Prof. Stoyan Bonev25 Expressions – Syntax Reg EXP and grammar to describe name RE = L.(L|D)* Grammar: I -> L | I L | I D L -> a | b | … | Z D -> 0 | 1 | 2 | … | 8 | 9

26 9/14/2015Assoc. Prof. Stoyan Bonev26 Expressions – Syntax Grammar to describe expression – see next slide

27 9/14/2015Assoc. Prof. Stoyan Bonev27 Expressions – Syntax Example of a grammar (ambiguous) ::= | | + | * ::= ::= | | ::= | ::= A | B | … | Z | a | b | … | z | _ ::= 0 | 1 | 2 | … | 9 How to interpret BNF notation? Expression is defined as a sole variable or as a sole constant, or as a sum of expressions, or as a product of expressions.

28 9/14/2015Assoc. Prof. Stoyan Bonev28 Expressions – Syntax Example of a grammar (non ambiguous) ::= | + ::= | * ::= | | ( ) ::= ::= | | ::= | ::= A | B | … | Z | a | b | … | z | _ ::= 0 | 1 | 2 | … | 9 How to interpret BNF notation? Expression is defined as a term or as a sum of terms. Term is defined as a factor or product of factors. Factor is defined as a var or as a const or as a sub expression surrounded in ( ).

29 9/14/2015Assoc. Prof. Stoyan Bonev29 Expressions – Syntax CFG or Extended CFG ::= | + ::= | * ::= | | ( ) ::= { + } * ::= { * } * ::= | | ( )

30 9/14/2015Assoc. Prof. Stoyan Bonev30 Expressions – Syntax Example of a grammar (non ambiguous) ::= { + }* ::= { * }* ::= | | ( ) ::= ::= | | ::= | ::= A | B | … | Z | a | b | … | z | _ ::= 0 | 1 | 2 | … | 9 How to interpret BNF notation? Expression is defined as a term or as a sum of terms. Term is defined as a factor or product of factors. Factor is defined as a var or as a const or as a sub expression surrounded in ( ).

31 9/14/2015Assoc. Prof. Stoyan Bonev31 Expressions – Semantics Semantics is the meaning of expressions. It is determined by how expressions are evaluated. Expression evaluation depends on the order of operator and operand evaluation. Operator evaluation order is controlled by the precedence rules and associativity rules of the PL. Specific topics in semantics of expressions: –Type Mismatches –Coercions –Short-Circuit Evaluation

32 9/14/2015Assoc. Prof. Stoyan Bonev32 Expressions Classification of expressions by category of operators: –Arithmetic expressions; –Relational expressions; –Boolean (Logical) expressions.

33 9/14/2015Assoc. Prof. Stoyan Bonev33 Arithmetic Expressions Purpose of AExp: to specify arithmetic computation. Implementation of such a computation must cause two actions: –fetching operands from memory, and –executing arithmetic operators on those operands In Programming Languages AExp consist of: –Operators – addition, subtraction, multiplication, division, modulus, power –Operands – constants, variables /scalar and indexed/, sub expressions, function calls

34 9/14/2015Assoc. Prof. Stoyan Bonev34 Operator evaluation order - Precedence Instead of simply evaluating the order from L to R or from R to L, the concept of placing operators in hierarchy of evaluation priorities was developed. Precedence(priority) rules define the order in which the operators of different precedence levels are evaluated.

35 9/14/2015Assoc. Prof. Stoyan Bonev35 AOp - Precedence Binary AOp: pow, mul, div, mod, add, sub – a + b + c – a * b * c * d / e / f % g – a + b * c – a + b * c ^ d

36 9/14/2015Assoc. Prof. Stoyan Bonev36 AOp - Precedence Unary AOp: –Unary addition or identity operator (+a). It has no associated operation and therefore no effect on its operand. (in Java the only effect is that byte/short operands are being implicitly converted to int). –Unary minus (-a) changes the sign of its operand. It can appear either at beginning or anywhere inside the expression, as long as it is parenthesized to prevent from being adjacent to another operator a + (-b) * c - legal a + -b * c - illegal

37 9/14/2015Assoc. Prof. Stoyan Bonev37 AOp - Precedence Precedence of AOp in some PL C-like PLAda Highest postfix ++, --**, abs prefix ++, --, unary +,-*, /, mod, rem *, /, %unary +, -binary +, - Lowest

38 9/14/2015Assoc. Prof. Stoyan Bonev38 Operator evaluation order - Associativity When an expression contains two or more adjacent operators (i.e. separated by one operand) the same precedence, it is the operator associativity to dictate the order of operator evaluation Left associativity:from L > R Right associativity:from R > L Nonassociativity (Ada): parentheses used in order to try to legalize the expression

39 9/14/2015Assoc. Prof. Stoyan Bonev39 Operator evaluation order - Associativity When an expression contains two or more adjacent operators (i.e. separated by one operand) the same precedence, it is the operator associativity to dictate the order of operator evaluation Left associativity:a+b-ca*b/c%d

40 9/14/2015Assoc. Prof. Stoyan Bonev40 Operator evaluation order - Associativity When an expression contains two or more adjacent operators (i.e. separated by one operand) the same precedence, it is the operator associativity to dictate the order of operator evaluation Right associativity:a**b**c

41 9/14/2015Assoc. Prof. Stoyan Bonev41 Operator evaluation order - Associativity When an expression contains two or more adjacent operators (i.e. separated by one operand) the same precedence, it is the operator associativity to dictate the order of operator evaluation Nonassociativity (Ada):a**b**c illegal and transformed to (a**b)**c ora**(b**c) in order to try to legalize the expression

42 9/14/2015Assoc. Prof. Stoyan Bonev42 Operator evaluation order - Associativity Unary – has precedence over binary –. – a – bis equivalent to(– a) – b Unary – has precedence over mul, div. – a * bis equivalent to (– a) * b – a / bis equivalent to (– a) / b Ada: exponentiation and modulus have precedence over unary minus. – a ** b is equivalent to – ( a ** b) – 17 mod 5is equivalent to – (17 mod 5)

43 9/14/2015Assoc. Prof. Stoyan Bonev43 AOp – Associativity in PL LanguageAssociativity Rules Visual BasicLeft:^, *, /, \, Mod, +, – Right: C-like PLLeft: *, /, %, binary+, binary– Right: ++, --, unary+, unary – AdaLeft: all except ** Nonassociative: ** FortranLeft:*, /, +, – Right: **

44 9/14/2015Assoc. Prof. Stoyan Bonev44 Operator evaluation order - Parentheses Programmers can alter precedence and associativity rules by placing parentheses in expressions a + b * cvs. ( a + b ) * c Parenthesized expressions have higher level of precedence. They are also called sub expressions and are being classified as valid operands.

45 9/14/2015Assoc. Prof. Stoyan Bonev45 Operator evaluation order – Conditional Expressions Unary, binary operators C-like PL: the ternary operator ? : How to describe a conditional expression. Ternary operator ? : average = (count==0) ? 0 : sum/count; Instead if (count == 0) average = 0; else average = sum/count;

46 9/14/2015Assoc. Prof. Stoyan Bonev46 Operand Evaluation Order Variables are evaluated by fetching their values from memory. Constants are sometimes evaluated by fetching their values from memory or a constant may be immediate operand in ML instruction and no need of a memory fetch. Operand evaluation order is irrelevant if neither of the operands of an operator has a side effect. Attention: Be careful on side effects

47 9/14/2015Assoc. Prof. Stoyan Bonev47 Operand Evaluation Order – Side Effects Definition: A side effect of a function (functional side effect) occurs when: the function changes either one of its parameters; the function changes a global variable.

48 9/14/2015Assoc. Prof. Stoyan Bonev48 Operand Evaluation Order – Side Effects Consider an expression a + fun(a) If fun does not have the side effect of changing a, then the order of evaluation of the operands a and fun(a) has no effect on the expression value. However, if fun changes a, there is an effect. Example: Consider fun returns the value of its argument divided by 2 and changes the value of its parameter to 20. Suppose source text: a = 10; b = a + fun(a); If the value of a is fetched first, b=10+fun(10)=10+5=15 If the second operand is evaluated first,b=20+fun(10)=20+5=25

49 9/14/2015Assoc. Prof. Stoyan Bonev49 Operand Evaluation Order – Side Effects One more example – C program illustrates side effect when function changes global variable that appears in an expression int a = 5; int fun1(){ a = 17; return 3; } void fun2(){ a = a + fun1(); } void main(){ fun2(); } The value computed for a in fun2 depends on the order of evaluation of the operands in the expression a+fun1(). The value of a will be either 8 or 20.

50 9/14/2015Assoc. Prof. Stoyan Bonev50 Operand Evaluation Order – Side Effects Two solutions to the problem of operand evaluation order: First, the language designer could disallow function evaluation from affecting the value of expressions by simply disallowing functional side effects. Second, to state in language definition that operands in expressions are to be evaluated in particular order and demand that language implementors guarantee that order.

51 9/14/2015Assoc. Prof. Stoyan Bonev51 Overloaded Operators Arithmetic operators are often used for more than one purpose. For example, + serves –to add integers, like5 + 8 –to add FP real values, like3.3 + 7.2 –to catenate strings (STL, Java), like“AU” + “BG” This multiple use is called operator overloading. Operator overloading is acceptable as long as readability and reliability do not suffer.

52 9/14/2015Assoc. Prof. Stoyan Bonev52 Type Conversions Type conversions classification: –Narrowing –Widening A narrowing conversion converts a value to a type that cannot even store approximations of all the values of the original type –E.g. converting double to float A widening conversion converts a value to a type that can include at least approximations of all the values of the original type –E.g. converting from int to float Widening conversions are usually safe Type conversions are either explicit or implicit

53 9/14/2015Assoc. Prof. Stoyan Bonev53 Implicit Type Conversion - Coercion A design decision concerning AExp is whether an operator can have operands of different types PL that allow mixed-mode expressions, must define conventions for implicit operand type conversions, called coercions Example: void myMethod() { int a, b, c;float d; a = b * d;... } Two implicit conversions take place: – b is converted to float – the r-value is converted to int, being truncated or eliminating the fraction part of the value

54 9/14/2015Assoc. Prof. Stoyan Bonev54 Explicit Type Conversion Most PL provide capabilities for doing explicit conversions, both widening and narrowing. In C-like PL, explicit type conversions are called casts using (type) operator – C/C++: (int)angle or applying so called functional notation –C++ only: int(angle)

55 9/14/2015Assoc. Prof. Stoyan Bonev55 Errors in Expressions A number of errors can occur in expression evaluation. If the PL requires type checking, then operand type errors cannot occur. Errors because of coercion of operands in expressions, e.g. loss of accuracy. Errors because result of an operation cannot be represented in the memory cell where it must be stored: –Overflow – result is too large –Underflow – result is too small

56 9/14/2015Assoc. Prof. Stoyan Bonev56 Relational Expressions A relational operator is an operator that compares the values of its two operands. A relational expression has two operands and one relational operator. The value of Relational Expression is Boolean, except when Boolean is not a type included in PL RelOp have lower precedence than AOp. a + 1 > 2 * b

57 9/14/2015Assoc. Prof. Stoyan Bonev57 Syntax of Relational Operators AdaC-like PL VBasic Fortran95 Equal ====.EQ. == Not equal /=!=<>.NE. <> Greater than >>>.GT. > Less than <<<.LT. < Greater than or equal >=>=>=.GE. >= Less than or equal <=<=<=.LE. <= JavaScript/PHP have two more relop === and !==. They are similar to == and != but prevent their operands from coercion “7” == 7 is true in JavaScript (string coerced to number) “7” === 7 is false in JavaScript (no coercion is done with this operator)

58 9/14/2015Assoc. Prof. Stoyan Bonev58 Associativity of RelOp From Left to Right One odd result in C’s design is that the following expression is legal a > b > c The leftmost > RelOp is evaluated first because of the left associativity, producing 0 or 1. Then this result is compared to the variable c. There is never comparison between b and c.

59 9/14/2015Assoc. Prof. Stoyan Bonev59 Boolean (Logical) Expressions Boolean expressions consist of Boolean variables, Boolean constants, relational expressions, and Boolean operators Boolean operators: AND, OR, NOT, and sometimes exclusive OR, and equivalence Precedence of Boolean operators: AND has higher precedence to OR. This results from baseless correlation of arithmetic multiplication with AND, and arithmetic addition with OR

60 9/14/2015Assoc. Prof. Stoyan Bonev60 Precedence of Ar,Rel,Bool Op C-like PL Highestpostfix ++, -- unary +,-, prefix ++, --, ! *, /, % binary +, -, = ==, != && Lowest||

61 9/14/2015Assoc. Prof. Stoyan Bonev61 Short-Circuit 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.

62 9/14/2015Assoc. Prof. Stoyan Bonev62 Short-Circuit Evaluation The value of the arithmetic expression (13*a)*(b/13-1) is independent of the sub expression (b/13-1) if a is 0, because 0*x=0 for any x. However, in AExp this shortcut is not easily detected during execution, so it is never taken.

63 9/14/2015Assoc. Prof. Stoyan Bonev63 Short-Circuit Evaluation The value of the Boolean expression (a>=0)&&(b<10) is independent of the second relational expression if a<0, because false&&x=false for any x. So, when a<0, there is no need to evaluate b, the constant 10, the second RelExp, or the && operator. Unlike the case of AExp, this shortcut can easily be detected during execution.

64 9/14/2015Assoc. Prof. Stoyan Bonev64 Assignment Operator/Statement

65 9/14/2015Assoc. Prof. Stoyan Bonev65 Assignment Operator/Statement Semantics: The purpose of an assignment operator ( statement ) is to change the value of a variable. An assignment statement can simply cause a value to be copied from one memory cell to another. In some cases assignment statement includes expressions with operators, which cause values to be copied to CPU and to be operated on, and the results to be copied back to memory.

66 9/14/2015Assoc. Prof. Stoyan Bonev66 Assignment Operator/Statement Syntax: Simple assignment: l-value =r-value :=

67 9/14/2015Assoc. Prof. Stoyan Bonev67 Assignment Operator/Statement Syntax: Simple assignment: l-value =r-value := a = 5 + 6 * 8

68 9/14/2015Assoc. Prof. Stoyan Bonev68 Assignment Operator/Statement Syntax: Simple assignment: l-value =r-value := a = 5 + 6 * 8 expression

69 9/14/2015Assoc. Prof. Stoyan Bonev69 Assignment Operator/Statement Syntax: Simple assignment: l-value =r-value := a = 5 + 6 * 8 expression a = 5 + 6 * 8 ; statement

70 9/14/2015Assoc. Prof. Stoyan Bonev70 Assignment Operator/Statement Multiple targets: C-like Programming Languages: a = b = c = d = 5 + 6 * 8; Pl/1, Ada: a, b, c, d = 5 + 6 * 8;

71 9/14/2015Assoc. Prof. Stoyan Bonev71 Assignment Operator/Statement Conditional targets: (flag) ? count1 = 0 : count2 = 0

72 9/14/2015Assoc. Prof. Stoyan Bonev72 Assignment Operator/Statement Compound assignment operators are a shorthand method of specifying a commonly needed form of assignment. The form of assignment that can be abbreviated with this technique has the destination variable also appearing as the first operand of the expression in the right side sum = sum + value is equivalent to sum += value The C-like languages have versions of the compound assignment operators for the most of their binary operators +=-=*=/=%=

73 9/14/2015Assoc. Prof. Stoyan Bonev73 Assignment Operator/Statement Two special unary arithmetic operators that are actually abbreviated assignments ++ and --. They combine increment and decrement operations with assignment and may be used in expressions or to form stand-alone single-operator assignment statement. ++count; count++; sum=++count;sum=count++; count=count+1;sum=count; sum=count;count=count+1;

74 9/14/2015Assoc. Prof. Stoyan Bonev74 Assignment Operator/Statement When two unary operators apply to the same operand, the association is R to L. - count ++ is equivalent to - (count ++) rather than (-count) ++

75 9/14/2015Assoc. Prof. Stoyan Bonev75 Assignment Operator/Statement Assignment as an Expression In C-like PL the assignment statement produces a result, which is the same as the value assigned to the target. It can therefore be used as an expression or as an operand in other expressions. This means that assignment operator is to be treated as the other binary operators except that it has the side effect of changing its left operand while ( ch = getchar() != EOF ) … while ( ( ch = getchar() ) != EOF ) …

76 9/14/2015Assoc. Prof. Stoyan Bonev76 Assignment Operator/Statement Assignment as an Expression: disadvantage: difficult to read and understand a = b + ( c = d / b++ ) - 1 assign b to temp assign b+1 to b assign d/temp to c assign b+c to temp assign temp-1 to a

77 9/14/2015Assoc. Prof. Stoyan Bonev77 Assignment Operator/Statement Assignment as an Expression: loss of error detection in the C PL design if ( x = y ) … if ( x == y ) …

78 9/14/2015Assoc. Prof. Stoyan Bonev78 Assignment–Conclusion Remark The very low level of precedence for the assignment operator The right associativity of the assignment operator The different notation for assignment operator and equality operator Mixed mode assignment

79 9/14/2015Assoc. Prof. Stoyan Bonev79 Exercise 5a Components of Programming Languages. Part II. Practical Operands, Operators, Expressions Assignments under discussion are based on lecture 3.

80 9/14/2015Assoc. Prof. Stoyan Bonev80 Task 1 Write a program to check the values of three real (float, double, and/or long double) variables as valid sides of a triangle using an expression with arithmetic, relational and boolean (logical) operators.

81 9/14/2015Assoc. Prof. Stoyan Bonev81 Task 2 Write a program to check an integer (short, int, long and/or unsigned) valued variable as a valid leap year.

82 9/14/2015Assoc. Prof. Stoyan Bonev82 Task 3 Write a program that copies its input to output (screen) one character at a time until end of data indicator EOF registered using getchar() built-in function.

83 9/14/2015Assoc. Prof. Stoyan Bonev83 Task 4 Verify that the expression getchar() != EOF is valued 0 or 1.

84 9/14/2015Assoc. Prof. Stoyan Bonev84 Precedence and associativity of operators in C/C++

85 ISBN 0-321-49362-1 Chapter 7 Expressions and Assignment Statements

86 Copyright © 2009 Addison-Wesley. All rights reserved.1-86Copyright © 2009 Addison-Wesley. All rights reserved.1-86 Chapter 7 Topics Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational and Boolean Expressions Short-Circuit Evaluation Assignment Statements Mixed-Mode Assignment

87 Copyright © 2009 Addison-Wesley. All rights reserved.1-87Copyright © 2009 Addison-Wesley. All rights reserved.1-87 Introduction Expressions are the fundamental means of specifying computations in a programming language To understand expression evaluation, need to be familiar with the orders of operator and operand evaluation Essence of imperative languages is dominant role of assignment statements

88 Copyright © 2009 Addison-Wesley. All rights reserved.1-88Copyright © 2009 Addison-Wesley. All rights reserved.1-88 Arithmetic Expressions Arithmetic evaluation was one of the motivations for the development of the first programming languages Arithmetic expressions consist of operators, operands, parentheses, and function calls

89 Copyright © 2009 Addison-Wesley. All rights reserved.1-89Copyright © 2009 Addison-Wesley. All rights reserved.1-89 Arithmetic Expressions: Design Issues Design issues for arithmetic expressions –Operator precedence rules? –Operator associativity rules? –Order of operand evaluation? –Operand evaluation side effects? –Operator overloading? –Type mixing in expressions?

90 Copyright © 2009 Addison-Wesley. All rights reserved.1-90Copyright © 2009 Addison-Wesley. All rights reserved.1-90 Arithmetic Expressions: Operators A unary operator has one operand A binary operator has two operands A ternary operator has three operands

91 Copyright © 2009 Addison-Wesley. All rights reserved.1-91Copyright © 2009 Addison-Wesley. All rights reserved.1-91 Arithmetic Expressions: Operator Precedence Rules The operator precedence rules for expression evaluation define the order in which “adjacent” operators of different precedence levels are evaluated Typical precedence levels – parentheses – unary operators – ** (if the language supports it) – *, / – +, -

92 Copyright © 2009 Addison-Wesley. All rights reserved.1-92Copyright © 2009 Addison-Wesley. All rights reserved.1-92 Arithmetic Expressions: Operator Associativity Rule The operator associativity rules for expression evaluation define the order in which adjacent operators with the same precedence level are evaluated Typical associativity rules –Left to right, except **, which is right to left –Sometimes unary operators associate right to left (e.g., in FORTRAN) APL is different; all operators have equal precedence and all operators associate right to left Precedence and associativity rules can be overriden with parentheses

93 Copyright © 2009 Addison-Wesley. All rights reserved.1-93Copyright © 2009 Addison-Wesley. All rights reserved.1-93 Ruby Expressions All arithmetic, relational, and assignment operators, as well as array indexing, shifts, and bit-wise logic operators, are implemented as methods - One result of this is that these operators can all be overriden by application programs

94 Copyright © 2009 Addison-Wesley. All rights reserved.1-94Copyright © 2009 Addison-Wesley. All rights reserved.1-94 Arithmetic Expressions: Conditional Expressions Conditional Expressions –C-based languages (e.g., C, C++) –An example: average = (count == 0)? 0 : sum / count –Evaluates as if written like if (count == 0) average = 0 else average = sum /count

95 Copyright © 2009 Addison-Wesley. All rights reserved.1-95Copyright © 2009 Addison-Wesley. All rights reserved.1-95 Arithmetic Expressions: Operand Evaluation Order Operand evaluation order 1.Variables: fetch the value from memory 2.Constants: sometimes a fetch from memory; sometimes the constant is in the machine language instruction 3.Parenthesized expressions: evaluate all operands and operators first 4.The most interesting case is when an operand is a function call

96 Copyright © 2009 Addison-Wesley. All rights reserved.1-96Copyright © 2009 Addison-Wesley. All rights reserved.1-96 Arithmetic Expressions: Potentials for Side Effects Functional side effects: when a function changes a two-way parameter or a non-local variable Problem with functional side effects: –When a function referenced in an expression alters another operand of the expression; e.g., for a parameter change: a = 10; /* assume that fun changes its parameter */ b = a + fun(&a);

97 Copyright © 2009 Addison-Wesley. All rights reserved.1-97Copyright © 2009 Addison-Wesley. All rights reserved.1-97 Functional Side Effects 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: inflexibility of one-way parameters and lack of non-local references 2.Write the language definition to demand that operand evaluation order be fixed Disadvantage: limits some compiler optimizations Java requires that operands appear to be evaluated in left-to-right order

98 Copyright © 2009 Addison-Wesley. All rights reserved.1-98Copyright © 2009 Addison-Wesley. All rights reserved.1-98 Overloaded Operators Use of an operator for more than one purpose is called operator overloading Some are common (e.g., + for int and float ) Some are potential trouble (e.g., * in C and C++) –Loss of compiler error detection (omission of an operand should be a detectable error) –Some loss of readability

99 Copyright © 2009 Addison-Wesley. All rights reserved.1-99Copyright © 2009 Addison-Wesley. All rights reserved.1-99 Overloaded Operators (continued) C++ and C# allow user-defined overloaded operators Potential problems: –Users can define nonsense operations –Readability may suffer, even when the operators make sense

100 Copyright © 2009 Addison-Wesley. All rights reserved.1-100Copyright © 2009 Addison-Wesley. All rights reserved.1-100 Type Conversions A narrowing conversion is one that converts an object to a type that cannot include all of the values of the original type e.g., float to int A widening conversion is one in which an object is converted to a type that can include at least approximations to all of the values of the original type e.g., int to float

101 Copyright © 2009 Addison-Wesley. All rights reserved.1-101Copyright © 2009 Addison-Wesley. All rights reserved.1-101 Type Conversions: Mixed Mode A mixed-mode expression is one that has operands of different types A coercion is an implicit type conversion Disadvantage of coercions: –They decrease in the type error detection ability of the compiler In most languages, all numeric types are coerced in expressions, using widening conversions In Ada, there are virtually no coercions in expressions

102 Copyright © 2009 Addison-Wesley. All rights reserved.1-102Copyright © 2009 Addison-Wesley. All rights reserved.1-102 Explicit Type Conversions Called casting in C-based languages Examples –C: (int)angle –Ada: Float (Sum) Note that Ada’s syntax is similar to that of function calls

103 Copyright © 2009 Addison-Wesley. All rights reserved.1-103Copyright © 2009 Addison-Wesley. All rights reserved.1-103 Type Conversions: Errors in Expressions Causes –Inherent limitations of arithmetic e.g., division by zero –Limitations of computer arithmetic e.g. overflow Often ignored by the run-time system

104 Copyright © 2009 Addison-Wesley. All rights reserved.1-104Copyright © 2009 Addison-Wesley. All rights reserved.1-104 Relational and Boolean Expressions Relational Expressions –Use relational operators and operands of various types –Evaluate to some Boolean representation –Operator symbols used vary somewhat among languages ( !=, /=, ~=,.NE., <>, # ) JavaScript and PHP have two additional relational operator, === and !== - Similar to their cousins, == and !=, except that they do not coerce their operands

105 Copyright © 2009 Addison-Wesley. All rights reserved.1-105Copyright © 2009 Addison-Wesley. All rights reserved.1-105 Relational and Boolean Expressions Boolean Expressions –Operands are Boolean and the result is Boolean –Example operators FORTRAN 77 FORTRAN 90C Ada.AND. and && and.OR. or || or.NOT. not ! not xor

106 Copyright © 2009 Addison-Wesley. All rights reserved.1-106Copyright © 2009 Addison-Wesley. All rights reserved.1-106 Relational and Boolean Expressions: No Boolean Type in C C89 has no Boolean type--it uses int type with 0 for false and nonzero for true One odd characteristic of C’s expressions: a < b < c is a legal expression, but the result is not what you might expect: –Left operator is evaluated, producing 0 or 1 –The evaluation result is then compared with the third operand (i.e., c )

107 Copyright © 2009 Addison-Wesley. All rights reserved.1-107Copyright © 2009 Addison-Wesley. All rights reserved.1-107 Short Circuit Evaluation An expression in which the result is determined without evaluating all of the operands and/or operators Example: (13*a) * (b/13–1) If a is zero, there is no need to evaluate (b/13-1) Problem with non-short-circuit evaluation index = 1; while (index <= length) && (LIST[index] != value) index++; –When index=length, LIST [index] will cause an indexing problem (assuming LIST has length -1 elements)

108 Copyright © 2009 Addison-Wesley. All rights reserved.1-108Copyright © 2009 Addison-Wesley. All rights reserved.1-108 Short Circuit Evaluation (continued) C, C++, and Java: use short-circuit evaluation for the usual Boolean operators ( && and || ), but also provide bitwise Boolean operators that are not short circuit ( & and | ) Ada: programmer can specify either (short-circuit is specified with and then and or else ) Short-circuit evaluation exposes the potential problem of side effects in expressions e.g. (a > b) || (b++ / 3)

109 Copyright © 2009 Addison-Wesley. All rights reserved.1-109Copyright © 2009 Addison-Wesley. All rights reserved.1-109 Assignment Statements The general syntax The assignment operator = FORTRAN, BASIC, the C-based languages := ALGOLs, Pascal, Ada = can be bad when it is overloaded for the relational operator for equality (that’s why the C-based languages use == as the relational operator)

110 Copyright © 2009 Addison-Wesley. All rights reserved.1-110Copyright © 2009 Addison-Wesley. All rights reserved.1-110 Assignment Statements: Conditional Targets Conditional targets (Perl) ($flag ? $total : $subtotal) = 0 Which is equivalent to if ($flag){ $total = 0 } else { $subtotal = 0 }

111 Copyright © 2009 Addison-Wesley. All rights reserved.1-111Copyright © 2009 Addison-Wesley. All rights reserved.1-111 Assignment Statements: Compound Operators A shorthand method of specifying a commonly needed form of assignment Introduced in ALGOL; adopted by C Example a = a + b is written as a += b

112 Copyright © 2009 Addison-Wesley. All rights reserved.1-112Copyright © 2009 Addison-Wesley. All rights reserved.1-112 Assignment Statements: Unary Assignment Operators Unary assignment operators in C-based languages combine increment and decrement operations with assignment Examples sum = ++count ( count incremented, added to sum ) sum = count++ ( count incremented, added to sum ) count++ ( count incremented) -count++ ( count incremented then negated)

113 Copyright © 2009 Addison-Wesley. All rights reserved.1-113Copyright © 2009 Addison-Wesley. All rights reserved.1-113 Assignment as an Expression In C, C++, and Java, the assignment statement produces a result and can be used as operands An example: while ((ch = getchar())!= EOF){ … } ch = getchar() is carried out; the result (assigned to ch ) is used as a conditional value for the while statement

114 Copyright © 2009 Addison-Wesley. All rights reserved.1-114Copyright © 2009 Addison-Wesley. All rights reserved.1-114 List Assignments Perl and Ruby support list assignments e.g., ($first, $second, $third) = (20, 30, 40);

115 Copyright © 2009 Addison-Wesley. All rights reserved.1-115Copyright © 2009 Addison-Wesley. All rights reserved.1-115 Mixed-Mode Assignment Assignment statements can also be mixed-mode In Fortran, C, and C++, any numeric type value can be assigned to any numeric type variable In Java, only widening assignment coercions are done In Ada, there is no assignment coercion

116 Copyright © 2009 Addison-Wesley. All rights reserved.1-116Copyright © 2009 Addison-Wesley. All rights reserved.1-116 Summary Expressions Operator precedence and associativity Operator overloading Mixed-type expressions Various forms of assignment

117 Thank You for Your attention


Download ppt "9/14/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 05 Components of Programming Languages, Part II Reference: R.Sebesta,"

Similar presentations


Ads by Google