Upcoming SlideShare
×

# 7 expressions and assignment statements

582 views

Published on

Published in: Technology
1 Like
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

Views
Total views
582
On SlideShare
0
From Embeds
0
Number of Embeds
28
Actions
Shares
0
0
0
Likes
1
Embeds 0
No embeds

No notes for slide

### 7 expressions and assignment statements

1. 1. ICS 313 - Fundamentals of Programming Languages 17. Expressions and Assignment Statements7.2 Arithmetic ExpressionsTheir evaluation was one of the motivations for thedevelopment of the first programming languagesArithmetic expressions consist of operators, operands,parentheses, and function callsDesign issues for arithmetic expressionsWhat are the operator precedence rules?What are the operator associativity rules?What is the order of operand evaluation?Are there restrictions on operand evaluation side effects?Does the language allow user-defined operator overloading?What mode mixing is allowed in expressions?
2. 2. ICS 313 - Fundamentals of Programming Languages 27.2 Arithmetic Expressions (continued)A unary operator has one operandA binary operator has two operandsA ternary operator has three operandsThe operator precedence rules for expression evaluation define theorder in which “adjacent” operators of different precedence levels areevaluated (“adjacent” means they are separated by at most oneoperand)Typical precedence levelsparenthesesunary operators** (if the language supports it)*, /+, -7.2 Arithmetic Expressions (continued)The operator associativity rules for expression evaluation define the order inwhich adjacent operators with the same precedence level are evaluatedTypical associativity rules:Left to right, except **, which is right to leftSometimes unary operators associate right to left (e.g., FORTRAN)APL is different; all operators have equal precedence and all operatorsassociate right to leftPrecedence and associativity rules can be overriden with parenthesesOperand evaluation orderThe process:Variables: just fetch the valueConstants: sometimes a fetch from memory; sometimes the constant is in themachine language instructionParenthesized expressions: evaluate all operands and operators firstFunction references: The case of most interest!Order of evaluation is crucial
3. 3. ICS 313 - Fundamentals of Programming Languages 37.2 Arithmetic Expressions (continued)Functional side effects - when a function changes atwo-way parameter or a nonlocal variableThe problem with functional side effects:When a function referenced in an expression altersanother operand of the expression e.g., for a parameterchange:a = 10;b = a + fun(&a);/* Assume that fun changes its parameter */Same problem with global variables7.2 Arithmetic Expressions (continued)Two Possible Solutions to the Problem:Write the language definition to disallow functional side effectsNo two-way parameters in functionsNo nonlocal references in functionsAdvantage: it works!Disadvantage: Programmers want the flexibility of two-way parameters (what aboutC?) and nonlocal referencesWrite the language definition to demand that operandevaluation order be fixedDisadvantage: limits some compiler optimizationsConditional ExpressionsC, C++, and Java (?:) e.g.average = (count == 0)? 0 : sum / count;
4. 4. ICS 313 - Fundamentals of Programming Languages 47.3 Overloaded OperatorsSome is common (e.g., + for int and float)Some is potential trouble (e.g., * in C and C++)Loss of compiler error detection (omission of an operandshould be a detectable error)Some loss of readabilityCan be avoided by introduction of new symbols (e.g., Pascal’sdiv)C++ and Ada allow user-defined overloaded operatorsPotential problems:Users can define nonsense operationsReadability may suffer, even when the operators make sense7.4 Type ConversionsA narrowing conversion is one that converts an object to a type thatcannot include all of the values of the original type e.g., float to intA widening conversion is one in which an object is converted to atype that can include at least approximations to all of the values ofthe original type e.g., int to floatA mixed-mode expression is one that has operands of different typesA coercion is an implicit type conversionThe disadvantage of coercions:They decrease in the type error detection ability of the compilerIn most languages, all numeric types are coerced in expressions,using widening conversionsIn Ada, there are virtually no coercions in expressions
5. 5. ICS 313 - Fundamentals of Programming Languages 57.4 Type Conversions (continued)Explicit Type ConversionsOften called casts e.g.Ada:FLOAT(INDEX) -- INDEX is INTEGER typeJava:(int)speed /* speed is float type */Errors in ExpressionsCaused by:Inherent limitations of arithmetic e.g. division by zeroLimitations of computer arithmetic e.g. overflowSuch errors are often ignored by the run-time system7.5 Relational and Boolean ExpressionsRelational Expressions:Use relational operators and operands of various typesEvaluate to some Boolean representationOperator symbols used vary somewhat among languages (!=, /=, .NE., <>,#)Boolean ExpressionsOperands are Boolean and the result is BooleanOperators:FORTRAN 77 FORTRAN 90 C Ada.AND. and && and.OR. or || or.NOT. not ! notxorC has no Boolean type--it uses int type with 0 for false and nonzero fortrueOne odd characteristic of C’s expressions: a < b < c is a legal expression,but the result is not what you might expect
6. 6. ICS 313 - Fundamentals of Programming Languages 67.5 Relational and Boolean Expressions (continued)Precedence of all Ada Operators:**, abs, not*, /, mod, remunary -, +binary +, -, &relops, in, not inand, or, xor, and then, or elseC, C++, and Java have over 40 operators and least15 different levels of precedence7.6 Short Circuit EvaluationSuppose Java did not use short-circuit evaluationProblem: table look-upindex = 1;while (index <= length) && (LIST[index] != value)index++;C, C++, and Java: use short-circuit evaluation for the usual Booleanoperators (&& and ||), but also provide bitwise Boolean operatorsthat are not short circuit (& and |)Ada: programmer can specify either (short-circuit is specified withand then and or else)FORTRAN 77: short circuit, but any side-affected place must be setto undefinedShort-circuit evaluation exposes the potential problem of side effectsin expressions e.g. (a > b) || (b++ / 3)
7. 7. ICS 313 - Fundamentals of Programming Languages 77.7 Assignment StatementsThe operator symbol:= FORTRAN, BASIC, PL/I, C, C++, Java:= ALGOLs, Pascal, Ada= Can be bad if it is overloaded for the relational operatorfor equalitye.g. (PL/I) A = B = C;Note difference from C7.7 Assignment Statements (continued)More complicated assignments:Multiple targets (PL/I)A, B = 10Conditional targets (C, C++, and Java)(first == true) ? total : subtotal = 0Compound assignment operators (C, C++, and Java)sum += next;Unary assignment operators (C, C++, and Java)a++;C, C++, and Java treat = as an arithmetic binary operatore.g.a = b * (c = d * 2 + 1) + 1This is inherited from ALGOL 68
8. 8. ICS 313 - Fundamentals of Programming Languages 87.7 Assignment Statements (continued)Assignment as an ExpressionIn C, C++, and Java, the assignment statementproduces a resultSo, they can be used as operands in expressionse.g. while ((ch = getchar() != EOF) { ... }DisadvantageAnother kind of expression side effect7.8 Mixed-Mode AssignmentIn FORTRAN, C, and C++, any numeric value canbe assigned to any numeric scalar variable;whatever conversion is necessary is doneIn Pascal, integers can be assigned to reals, butreals cannot be assigned to integers (theprogrammer must specify whether the conversionfrom real to integer is truncated or rounded)In Java, only widening assignment coercions aredoneIn Ada, there is no assignment coercion