Expressions and Assignment Statements

whooploafΛογισμικό & κατασκευή λογ/κού

13 Δεκ 2013 (πριν από 3 χρόνια και 7 μήνες)

70 εμφανίσεις

ISBN 0
-
321
-
33025
-
0

Chapter 7

Expressions and

Assignment
Statements

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
2

Chapter 7 Topics


Introduction


Arithmetic Expressions


Overloaded Operators


Type Conversions


Relational and Boolean Expressions


Short
-
Circuit Evaluation


Assignment Statements


Mixed
-
Mode Assignment

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
3

Introduction


Expressions are the fundamental means of
specifying computations in a programming
language


Expressions are motivation for early language

imperative language

dominant role: assignment

must understand:



order of operators



operand evaluation

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
4

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


mode mixing expressions

more

interesting

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
5

Arithmetic Expressions: Operators

operators

unary

(1 operand)

binary

(2 operands)

ternary

(3 operands)

infix
-

most

prefix
-

Scheme

typical precedence:



parentheses



unary operators



** (if the language supports it,


Fortran, Ruby, VB and Ada do)



*, /, %



+,
-


Typical associativity rules


Left to right, except assignment and
**, which are right to left


Sometimes unary operators associate
right to left (e.g., in FORTRAN and
C
-
based, ++ and
--
, also =)



APL is different; all operators have equal precedence and all operators
associate right to left, precedence and associativity rules can be overridden
with parentheses


would this be more or less confusing?

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
6

Arithmetic Expressions: Conditional
Expressions


Conditional Expressions


C
-
based languages (e.g., C, C++)


Also in Perl, JavaScript and Ruby


An example:



average = (count == 0)? 0 : sum / count



Evaluates as if written like



if (count == 0)




average = 0



else




average = sum /count





Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
7

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 same expression; e.g., for a parameter change:



a = 10;




b = a + fun(a);




void fun(int& a) { a = 15; }



What value will b have after the above statements are
executed?




https://www.securecoding.cert.org/

The order in which operands in an expression are evaluated is unspecified in C++. The only guarantee is that they will
all be completely evaluated at the next
sequence point
.

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
8

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

2.
Write the language definition to demand that
operand evaluation order be fixed


Disadvantage
: limits some compiler optimizations*

*
compilers draw graphs to detect when values are created/modified

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
9

Referential Transparency


A program has the property of
referential transparency

if any two
expressions in the program with same value can be substituted
for one another anywhere, without affecting the action of the
program.

result1 = (
fun(a)

+ b / (
fun(a)



c);

temp =
fun(a)
;

result2 = (temp + b) / (temp


c);



If fun has no side effects, result1 and result2 are equal. If fun
modifies b or c, then not equal, violates referential transparency.


Functional languages are referentially transparent, easier to
reason about, more like math functions
.

Copyright © 2006 Addison
-
Wesley. All rights reserved.

Overloaded Operators


& as address vs
bitwise AND

ptr = &y;

if (x & y == 0) …


-

unary vs binary

z =
-
x + y;

z = x


-
y;




Integer vs floating
point division

avg = sum/count;


Pascal avoided:

avg = sum div count;

would this be a good idea

in C++/Java?

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
11

Overloaded Operators (continued)


C++, Ruby, Ada and C# allow user
-
defined
overloaded operators


Overloading was not included in Java


Potential problems:


Users can define nonsense operations


Readability may suffer, even when the operators
make sense


Should it have been?

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
12

Type Conversions


Widening

Conversions:
can include at least approximations to all of the
values of the original type


byte to short, int, long, float or double


short to int, long, float or double


char to int, long, float or double


int to long, float or double


long to float or double


float to double


Narrowing

conversions:
cannot include all of the values of the original
type


short to byte or char


char to byte or short


int to byte, short, or char


long to byte, short, char or int


float to byte, short, char, int or long


double to byte, short, char, int, long or float

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
13

Type conversions


dangerous?


Even widening conversions may lose
accuracy. Example: integers stored in 32
bits, 9 digits of precision. Floating point
values also stored in 32 bits, only about 7
digits of precision (because of space used
for exponent).

Conversions should be used with care! Warnings should

not just be ignored…

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
14

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 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

Ada is strongly typed

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
15

Explicit Type Conversions


Explicit Type Conversions


Called
casting

in C
-
based language


Examples


C: (int) angle


Ada: Float (sum)



Note that Ada’s syntax is similar to function
calls


may be better because casting does have
associated code (convert bit patterns)

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
16

Relational and Boolean Expressions


Relational Expressions


Use relational operators and operands of various
types


Evaluate to some Boolean representation

How do you say “not equal”?

!=

/=

#

<>

.NE.

Do you want to coerce that?

!==

===

eql?

Leave me like you

find me!

(JavaScript/Perl)

Ruby

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
17

Relational and Boolean Expressions


Boolean Expressions


Operands are Boolean and the result is Boolean


AND and OR have equal precedence in some
languages, not others (AND higher in C++)


FORTRAN 77 FORTRAN 90


C Ada


.AND. and && and


.OR. or || or


.NOT. not ! not


xor

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
18

Relational and Boolean Expressions
-

review


C has no Boolean type (0=false, >0 = true)


SO:
a < b < c

is a legal expression


but is the result what you want????


(a < b) => produces 0 or 1


(0 < c) OR (1 < c)
Who cares whether 0 < c ???



Some error detection is lost if no Boolean
type

How is a < b < c evaluated by compiler in Java?

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
19

Short Circuit Evaluation
-

review


An expression in which the result is
determined without evaluating all of the
operands and/or operators


(a >= 0) && (b < 10)


Problem with non
-
short
-
circuit evaluation:

index = 0;

while ((index < length) && (LIST[index] != value))


index++;


When

index=length,

LIST

[index]

will cause an
indexing problem (assuming last index of
LIST

is
length

-
1
)

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
20

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
|
)


Ruby, Perl and Python are short
-
circuit evaluated


Short
-
circuit is a choice in Ada


Short
-
circuit evaluation exposes the potential
problem of side effects in expressions

e.g.
(a > b) || (b++ / 3)

will b be incremented or not?

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
21

Assignment Statements


The general syntax

<target_var> <assign_operator> <expression>


The assignment operator

=

FORTRAN, BASIC, PL/I, C, C++, Java

:=

ALGOLs, Pascal, Ada


= can be bad when it is overloaded for the
relational operator for equality


confusing for beginners even when it’s not
overloaded

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
22

Assignment Statements: Conditional
Targets


Conditional targets (C, C++, and Java)

(flag)? total : subtotal = 0


Which is equivalent to


if (flag)


total = 0

else


subtotal = 0



Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
23

Assignment Statements: Shorthand Syntax


Adding two values:

a = a + b

is written as

a += b


Introduced in ALGOL; adopted by C, Perl, JavaScript, Python and
Ruby


Incrementing or decrementing:


int count=4;


int sum=++count; // increment then use


int count2=4;


int sum2=count2++; // use then increment


cout << sum << " " << sum2 << endl; // 5 4


count++

(
count

incremented)


-
count++

(
count

incremented then negated)


Included in C
-
based languages, Perl and JavaScript


Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
24

Assignment as an Expression


In C, C++, Java, Perl and JavaScript the
assignment statement produces a result
and can be used as operand


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; must be in
(); can be harder to read

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
25

List Assignments


Some recent languages like Perl and Ruby
provide multiple
-
target, multiple
-
source
assignments


In Perl:

($first, $second, $third) = (20, 30, 30);

($first, $second) = ($second, $first);

excess values on right ignored

excess values on left set to undef

How useful is this feature?

Copyright © 2006 Addison
-
Wesley. All rights reserved.

1
-
26

Mixed
-
Mode Assignment


Assignment statements can also be
mixed
-
mode, for example

int a, b;

float c;

c = a / b;


Coercion takes place after rhs evaluated


Fortran, C, C++ and Perl use coercion
rules for mixed mode assignment


In Java, only widening assignment
coercions are done (increases reliability)


In Ada, there is no assignment coercion