Expressions and Assignment Statements Operator Precedence
Total Page:16
File Type:pdf, Size:1020Kb
Chapter 6 - Expressions and Operator Precedence Assignment Statements • A unary operator has one operand • Their evaluation was one of the motivations for • A binary operator has two operands the development of the first PLs • A ternary operator has three operands • Arithmetic expressions consist of operators, operands, parentheses, and function calls The operator precedence rules for expression evaluation define the order in which “adjacent” Design issues for arithmetic expressions: operators of different precedence levels are 1. What are the operator precedence rules? evaluated 2. What are the operator associativity rules? – “adjacent” means they are separated by at 3. What is the order of operand evaluation? most one operand 4. Are there restrictions on operand evaluation side effects? Typical precedence levels: 5. Does the language allow user-defined operator 1. parentheses overloading? 2. unary operators 6. What mode mixing is allowed in expressions? 3. ** (if the language supports it) 4. *, / 5. +, - Chapter 6 Programming 1 Chapter 6 Programming 2 Languages Languages Operator Associativity Operand Evaluation Order The operator associativity rules for expression The process: evaluation define the order in which adjacent 1. Variables: just fetch the value operators with the same precedence level are evaluated 2. Constants: sometimes a fetch from memory; sometimes the constant is in the machine Typical associativity rules: language instruction • Left to right, except **, which is right to left • Sometimes unary operators associate right to 3. Parenthesized expressions: evaluate all left (e.g., FORTRAN) operands and operators first - APL is different; all operators have equal 4. Function references: The case of most interest! precedence and all operators associate right to - Order of evaluation is crucial left Use of Parantheses Precedence and associativity rules can be overridden with parentheses Chapter 6 Programming 3 Chapter 6 Programming 4 Languages Languages Functional Side Effects Conditional Expressions When a function changes a two-way parameter or C, C++, and Java a nonlocal variable. • ?: ternary operator The problem with functional side effects: average = (count==0)? 0 : sum/count; • When a function referenced in an expression alters another operand of the expression e.g., for a parameter change: Operator Overloading a = 10; • Some is common (e.g., + for int and float) b = a + fun(&a); • Some is potential trouble (e.g., * in C and C++) /* Assume that fun changes its parameter */ • Loss of compiler error detection (omission of an operand should be a detectable error) Two Possible Solutions to the Problem: 1. Write the language definition to disallow functional side effects. • Can be avoided by introduction of new symbols (e.g., Pascal’s div) – No two-way parameters in functions – No nonlocal references in functions • C++ and Ada allow user-defined overloaded – Advantage: it works! operators – Disadvantage: Programmers want the Potential problems: flexibility of two-way parameters (what about C?) and nonlocal references – Users can define nonsense operations 2. Write the language definition to demand that – Readability may suffer operand evaluation order be fixed – Disadvantage: limits some compiler optimizations Chapter 6 Programming 5 Chapter 6 Programming 6 Languages Languages 1 Implicit Type Conversions Explicit Type Conversions • A narrowing conversion is one that converts Often called casts an object to a type that cannot include all of the • e.g. Ada: values of the original type FLOAT(INDEX) -- INDEX is an INTEGER • A widening conversion is one in which an • e.g. C: object is converted to a type that can include at least approximations to all of the values of the (int)speed /*speed is float type*/ original type Errors in Expressions • A mixed-mode expression is one that has Caused by: operands of different types. • Inherent limitations of arithmetic e.g. division by zero • A coercion is an implicit type conversion. • Limitations of computer arithmetic The disadvantage of coercions: e.g. overflow • They decrease in the type error detection ability of the compiler Such errors are often ignored by the run-time system • In most languages, all numeric types are coerced in expressions, using widening conversions • In Modula-2 and Ada, there are virtually no coercions in expressions Chapter 6 Programming 7 Chapter 6 Programming 8 Languages Languages Relational Expressions Boolean Expressions • Use relational operators and operands of • Operands are Boolean and the result is Boolean. various types • Operators: • Evaluate to some Boolean representation F77 F90 C Ada • Operator symbols used vary somewhat among .AND. and && and languages .OR. or || or (!=, /=, .NE., <>, #) .NOT. not ! not xor Relational operators always have lower Common Precedence order: NOT, AND, OR. precedence than the arithmetic operators: e.g., a+1 > 2*b º (a+1) > (2*b) Ada: logical ops have same precedence and no assoc! C: has no boolean type--it uses int type with 0 for false and nonzero for true. no Boolean Þ low readablity, lost error detection One odd characteristic of C’s expressions: a < b < c is a legal expression, but the result is not what you might expect! Chapter 6 Programming 9 Chapter 6 Programming 10 Languages Languages Precedence of All Operators Short Circuit Evaluation Arith.exprs can be operands of rel. exprs and Result is determined without evaluating all of the rel.exprs can be operands of Boolean exprs. operands and/or operators. e.g. (13 * A) * (B / 13 - 1) or (A >= 0) and (B < 10) Common Precedence order: Pascal: does not use short-circuit evaluation Arithmetic, relative, logical Þ Problem: table look-up using while statement. index := 1; Pascal: (boolean exprs. has higher precedence while (index <= length) and than rel exprs.) (LIST[index] <> value) do not, unary - index := index + 1 *, /, div, mod, and +, -, or C, C++, and Java: use short-circuit evaluation for the usual Boolean operators (&& and ||), but relops also provide bitwise Boolean operators that are Ada: not short circuit (& and |) ** Ada: programmer can specify either (short-circuit *, /, mod, rem is specified with and thenand or else) unary -, not **This is the best design choice! +, -, & relops FORTRAN 77: short circuit, but any side-affected and, or, xor place must be set to undefined. C, C++, and Java have over 50 operators and • Short-circuit evaluation exposes the potential 17 different levels of precedence. problem of side effects in expressions e.g. (a > b) || (b++ / 3) Chapter 6 Programming 11 Chapter 6 Programming 12 Languages Languages 2 Assignment Statements How Assignments are Used? • provides a mechanism by which the user can More complicated assignments: dynamically change the bindings of values to 1. Multiple targets variables. A, B = 10 (PL/I) (can be simulated in C) The operator symbol: 2. Conditional targets (C, C++, and Java) FORTRAN, BASIC, PL/I, C, C++, Java = (first==true) ? total : subtotal=0 Þ can be bad if = is overloaded for the relational operator for equality 3. Compound assignment operators (C, C++, e.g. (PL/I) A = B = C; and Java) := ALGOLs, Pascal, Modula-2, Ada sum += next; 4. Unary assignment operators (C, C++, and The assignment operator in C and C++ is Java) (prefix or postfix) treated much like a binary operator, and as a++; much it can appear embedded in expressions. C/C++/Java treat = as an arithmetic binary operator: We will see the other design choices... e.g. a = b * (c = d * 2 + 1) + 1 This is inherited from ALGOL 68 When two unary operators apply to the same operand, the association is right to left: e.g. - count ++ Chapter 6 Programming 13 Chapter 6 Programming 14 Languages Languages Assignment as an Expression Mixed-Mode Assignment In C, C++, and Java, the assignment statement produces a result • In FORTRAN, C, and C++, any numeric value – So, they can be used as operands in can be assigned to any numeric scalar ariable; expressions whatever conversion is necessary is done e.g. while ((ch=getchar()!=EOF){...} • In Pascal, integers can be assigned to reals, • Disadvantage but not vice versa (the programmer must specify whether the conversion from real to – Another kind of expression side effect integer is truncated or rounded) – Difficult to read and understand e.g., a = b + (c = d / b++) - 1 • In Java, only widening assignment coercions are done C’s assignment operator allows the effect of • In Ada, there is no assignment coercion. multiple-target assignments: e.g., sum = count = 0; Low safety of = operator in C/C++: Loss of error detectin in the C design of the assignment operation that frequently leades to program errors: e.g., if (x = y) ... Chapter 6 Programming 15 Chapter 6 Programming 16 Languages Languages 3.