9/14/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 05 Components of...
-
Upload
ilene-marianna-ramsey -
Category
Documents
-
view
214 -
download
1
Transcript of 9/14/2015Assoc. Prof. Stoyan Bonev1 COS220 Concepts of PLs AUBG, COS dept Lecture 05 Components of...
04/19/23 Assoc. Prof. Stoyan Bonev 1
COS220 Concepts of PLs AUBG, COS dept
Lecture 05
Components of Programming
Languages, Part II
Reference: R.Sebesta, Chapter 7
04/19/23 Assoc. Prof. Stoyan Bonev 2
Lecture Contents:
• Expressions • Operands within Expressions• Operators within Expressions• The Assignment Operator• The Assignment Statement
04/19/23 Assoc. Prof. Stoyan Bonev 3
Expressions
Expressions are defined as entities composed to contain operands and operators that specify some computation.
04/19/23 Assoc. Prof. Stoyan Bonev 4
Expressions - Operands
Typical operands:
• Literals: 34, 5.68, -.567
04/19/23 Assoc. Prof. Stoyan Bonev 5
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
04/19/23 Assoc. Prof. Stoyan Bonev 6
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/
04/19/23 Assoc. Prof. Stoyan Bonev 7
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;
04/19/23 Assoc. Prof. Stoyan Bonev 8
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)
04/19/23 Assoc. Prof. Stoyan Bonev 9
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)
04/19/23 Assoc. Prof. Stoyan Bonev 10
Expressions - Operators
Formal characteristics of operators:
• Precedence;
04/19/23 Assoc. Prof. Stoyan Bonev 11
Expressions - Operators
Formal characteristics of operators:
• Precedence;
• Associativity;
04/19/23 Assoc. Prof. Stoyan Bonev 12
Expressions - Operators
Formal characteristics of operators:• Precedence;• Associativity; • Number of operands:
– Unary – a sole operand– Binary – two operands– Ternary – three operands
04/19/23 Assoc. Prof. Stoyan Bonev 13
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).
04/19/23 Assoc. Prof. Stoyan Bonev 14
No
Operator Associativity
1 ( ) [ ] –>.
L→R
2 ! ~ ++ –– + –* & (type) sizeof
R→L
3 * / % L→R
4 + – L→R
5 << >> L→R
6 < <= > >= L→R
7 == != L→R
8 & L→R
9 ^ L→R
10 | L→R
11 && L→R
12 || L→R
13 ? : L→R
14 = += –= *= /= %=&= |= <<= >>=
R→L
15 , L→R
04/19/23 Assoc. Prof. Stoyan Bonev 15
Expressions – Syntax
• Intro to BNF
• Intro to Backus Naur Form
• Intro to Backus Normal Form
04/19/23 Assoc. Prof. Stoyan Bonev 16
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.
04/19/23 Assoc. Prof. Stoyan Bonev 17
Expressions – Syntax
Do you remember the Reg EXP concept to describe integer/real literals (operands of expressions)
04/19/23 Assoc. Prof. Stoyan Bonev 18
Expressions – Syntax
Do you remember the Reg EXP concept to describe integer/real literals (operands of expressions)
D+
D+.D* | D*.D+
04/19/23 Assoc. Prof. Stoyan Bonev 19
Expressions – Syntax
Do you remember the Reg EXP concept to describe names/identifiers of variables (operands of expressions)
04/19/23 Assoc. Prof. Stoyan Bonev 20
Expressions – Syntax
Do you remember the Reg EXP concept to describe names/identifiers of variables (operands of expressions)
L.(L|D)*
04/19/23 Assoc. Prof. Stoyan Bonev 21
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
04/19/23 Assoc. Prof. Stoyan Bonev 22
Expressions – Syntax
Reg EXP and grammar to describe integer literal
RE = D+
Grammar:<Constant> ::= <Digit> | <Constant> <Digit>
<Digit> ::= 0 | 1 | 2 | … | 8 | 9
04/19/23 Assoc. Prof. Stoyan Bonev 23
Expressions – Syntax
Reg EXP and grammar to describe integer literal
RE = D+
Grammar:
C -> D | C D
D -> 0 | 1 | 2 | … | 8 | 9
04/19/23 Assoc. Prof. Stoyan Bonev 24
Expressions – Syntax
Reg EXP and grammar to describe name
RE = L.(L|D)*
Grammar:
<Id> ::= <let> | <Id><let> | <Id><dig>
<let> ::= a | b | … | Z
<dig> ::= 0 | 1 | 2 | … | 8 | 9
04/19/23 Assoc. Prof. Stoyan Bonev 25
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
04/19/23 Assoc. Prof. Stoyan Bonev 26
Expressions – Syntax
Grammar to describe expression – see next slide
04/19/23 Assoc. Prof. Stoyan Bonev 27
Expressions – Syntax
Example of a grammar (ambiguous)<Expr> ::= <Var> | <Const> | <Expr> + <Expr> | <Expr> * <Expr>
<Var> ::= <Ident>
<Ident> ::= <Letter> | <Ident><Letter> | <Ident><Digit>
<Const> ::= <Digit> | <Const><Digit>
<Letter> ::= A | B | … | Z | a | b | … | z | _
<Digit> ::= 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.
04/19/23 Assoc. Prof. Stoyan Bonev 28
Expressions – SyntaxExample of a grammar (non ambiguous)<Expr> ::= <Term> | <Expr> + <Term><Term> ::= <Factor> | <Term> * <Factor><Factor> ::= <Var> | <Const> | ( <Expr> )<Var> ::= <Ident><Ident> ::= <Letter> | <Ident><Letter> | <Ident><Digit><Const> ::= <Digit> | <Const><Digit><Letter> ::= A | B | … | Z | a | b | … | z | _<Digit> ::= 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 ( ).
04/19/23 Assoc. Prof. Stoyan Bonev 29
Expressions – SyntaxCFG or Extended CFG
<Expr> ::= <Term> | <Expr> + <Term><Term> ::= <Factor> | <Term> * <Factor><Factor> ::= <Var> | <Const> | ( <Expr> )
<Expr> ::= <Term> { + <Term> } *<Term> ::= <Factor> { * <Factor> } *<Factor> ::= <Var> | <Const> | ( <Expr> )
04/19/23 Assoc. Prof. Stoyan Bonev 30
Expressions – SyntaxExample of a grammar (non ambiguous)<Expr> ::= <Term> { + <Term> }*<Term> ::= <Factor> { * <Factor> }*<Factor> ::= <Var> | <Const> | ( <Expr> )<Var> ::= <Ident><Ident> ::= <Letter> | <Ident><Letter> | <Ident><Digit><Const> ::= <Digit> | <Const><Digit><Letter> ::= A | B | … | Z | a | b | … | z | _<Digit> ::= 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 ( ).
04/19/23 Assoc. Prof. Stoyan Bonev 31
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
04/19/23 Assoc. Prof. Stoyan Bonev 32
Expressions
• Classification of expressions by category of operators:– Arithmetic expressions;
– Relational expressions;
– Boolean (Logical) expressions.
04/19/23 Assoc. Prof. Stoyan Bonev 33
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
04/19/23 Assoc. Prof. Stoyan Bonev 34
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.
04/19/23 Assoc. Prof. Stoyan Bonev 35
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
04/19/23 Assoc. Prof. Stoyan Bonev 36
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
04/19/23 Assoc. Prof. Stoyan Bonev 37
AOp - Precedence
• Precedence of AOp in some PL
C-like PL AdaHighest
postfix ++, -- **, abs
prefix ++, --, unary +,- *, /, mod, rem
*, /, % unary +, -
binary +, - binary +, -
Lowest
04/19/23 Assoc. Prof. Stoyan Bonev 38
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
04/19/23 Assoc. Prof. Stoyan Bonev 39
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-c a*b/c%d
04/19/23 Assoc. Prof. Stoyan Bonev 40
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
04/19/23 Assoc. Prof. Stoyan Bonev 41
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 or a**(b**c)in order to try to legalize the expression
04/19/23 Assoc. Prof. Stoyan Bonev 42
Operator evaluation order - Associativity
• Unary – has precedence over binary –.• – a – b is equivalent to (– a) – b
• Unary – has precedence over mul, div.• – a * b is equivalent to (– a) * b• – a / b is equivalent to (– a) / b
• Ada: exponentiation and modulus have precedence over unary minus.
• – a ** b is equivalent to – ( a ** b)• – 17 mod 5 is equivalent to – (17 mod 5)
04/19/23 Assoc. Prof. Stoyan Bonev 43
AOp – Associativity in PL
Language Associativity RulesVisual Basic Left: ^, *, /, \, Mod, +, –
Right:C-like PL Left: *, /, %, binary+, binary–
Right: ++, --, unary+, unary –Ada Left: all except **
Nonassociative: **Fortran Left: *, /, +, –
Right: **
04/19/23 Assoc. Prof. Stoyan Bonev 44
Operator evaluation order - Parentheses
• Programmers can alter precedence and associativity rules by placing parentheses in expressions
a + b * c vs. ( a + b ) * c
• Parenthesized expressions have higher level of precedence. They are also called sub expressions and are being classified as valid operands.
04/19/23 Assoc. Prof. Stoyan Bonev 45
Operator evaluation order – Conditional Expressions
• Unary, binary operators• C-like PL: the ternary operator ? :• How to describe a conditional expression.
Ternary operator
<expression1> ? <expression2> : <expression3>
average = (count==0) ? 0 : sum/count;
Instead if (count == 0) average = 0;
else average = sum/count;
04/19/23 Assoc. Prof. Stoyan Bonev 46
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
04/19/23 Assoc. Prof. Stoyan Bonev 47
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.
04/19/23 Assoc. Prof. Stoyan Bonev 48
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=15If the second operand is evaluated first,
b=20+fun(10)=20+5=25
04/19/23 Assoc. Prof. Stoyan Bonev 49
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.
04/19/23 Assoc. Prof. Stoyan Bonev 50
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.
04/19/23 Assoc. Prof. Stoyan Bonev 51
Overloaded Operators
• Arithmetic operators are often used for more than one purpose. For example, + serves– to add integers, like 5 + 8
– to add FP real values, like 3.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.
04/19/23 Assoc. Prof. Stoyan Bonev 52
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
04/19/23 Assoc. Prof. Stoyan Bonev 53
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
04/19/23 Assoc. Prof. Stoyan Bonev 54
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)
04/19/23 Assoc. Prof. Stoyan Bonev 55
Errors in ExpressionsA 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
04/19/23 Assoc. Prof. Stoyan Bonev 56
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
04/19/23 Assoc. Prof. Stoyan Bonev 57
Syntax of Relational Operators
Ada C-like PL VBasic Fortran95Equal = == = .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)
04/19/23 Assoc. Prof. Stoyan Bonev 58
Associativity of RelOp
• From Left to Right
• One odd result in C’s design is that the following expression is legal
• a > b > cThe 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.
04/19/23 Assoc. Prof. Stoyan Bonev 59
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
04/19/23 Assoc. Prof. Stoyan Bonev 60
Precedence of Ar,Rel,Bool Op
C-like PLHighest postfix ++, --
unary +,-, prefix ++, --, !
*, /, %
binary +, -
<, >, <=, >=
==, !=
&&
Lowest ||
04/19/23 Assoc. Prof. Stoyan Bonev 61
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.
04/19/23 Assoc. Prof. Stoyan Bonev 62
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.
04/19/23 Assoc. Prof. Stoyan Bonev 63
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.
04/19/23 Assoc. Prof. Stoyan Bonev 64
Assignment
Operator/Statement
04/19/23 Assoc. Prof. Stoyan Bonev 65
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.
04/19/23 Assoc. Prof. Stoyan Bonev 66
Assignment Operator/Statement
Syntax:
Simple assignment:<target variable> <assignment oprtor> <expression>
l-value = r-value
:=
04/19/23 Assoc. Prof. Stoyan Bonev 67
Assignment Operator/Statement
Syntax:
Simple assignment:<target variable> <assignment operator> <expression>
l-value = r-value
:=
a = 5 + 6 * 8
04/19/23 Assoc. Prof. Stoyan Bonev 68
Assignment Operator/Statement
Syntax:
Simple assignment:<target variable> <assignment operator> <expression>
l-value = r-value
:=
a = 5 + 6 * 8 expression
04/19/23 Assoc. Prof. Stoyan Bonev 69
Assignment Operator/Statement
Syntax:Simple assignment:<target variable> <assignment operator> <expression>
l-value = r-value :=
a = 5 + 6 * 8 expressiona = 5 + 6 * 8 ; statement
04/19/23 Assoc. Prof. Stoyan Bonev 70
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;
04/19/23 Assoc. Prof. Stoyan Bonev 71
Assignment Operator/Statement
Conditional targets:
(flag) ? count1 = 0 : count2 = 0
04/19/23 Assoc. Prof. Stoyan Bonev 72
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
+= -= *= /= %=
04/19/23 Assoc. Prof. Stoyan Bonev 73
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;
04/19/23 Assoc. Prof. Stoyan Bonev 74
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) ++
04/19/23 Assoc. Prof. Stoyan Bonev 75
Assignment Operator/Statement
Assignment as an ExpressionIn 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 ) …
04/19/23 Assoc. Prof. Stoyan Bonev 76
Assignment Operator/Statement
Assignment as an Expression: disadvantage: difficult to read and understand
a = b + ( c = d / b++ ) - 1
assign b to tempassign b+1 to bassign d/temp to cassign b+c to tempassign temp-1 to a
04/19/23 Assoc. Prof. Stoyan Bonev 77
Assignment Operator/Statement
Assignment as an Expression: loss of error detection in the C PL design
if ( x = y ) …
if ( x == y ) …
04/19/23 Assoc. Prof. Stoyan Bonev 78
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
04/19/23 Assoc. Prof. Stoyan Bonev 79
Exercise 5a
Components of Programming Languages. Part II.
Practical
• Operands, Operators, Expressions
Assignments under discussion are based on lecture 3.
04/19/23 Assoc. Prof. Stoyan Bonev 80
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.
04/19/23 Assoc. Prof. Stoyan Bonev 81
Task 2
Write a program to check an integer (short, int, long and/or unsigned) valued variable as a valid leap year.
04/19/23 Assoc. Prof. Stoyan Bonev 82
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.
04/19/23 Assoc. Prof. Stoyan Bonev 83
Task 4
Verify that the expression getchar() != EOF is valued 0 or 1.
04/19/23 Assoc. Prof. Stoyan Bonev 84
Precedence and associativity of operators in C/C++
No Operator Associativity
1 ( ) [ ] –> . L→R
2 ! ~ ++ –– + – * & (type) sizeof R→L
3 * / % L→R
4 + – L→R
5 << >> L→R
6 < <= > >= L→R
7 == != L→R
8 & L→R
9 ^ L→R
10 | L→R
11 && L→R
12 || L→R
13 ? : L→R
14 = += –= *= /= %= &= |= <<= >>= R→L
15 , L→R
ISBN 0-321-49362-1
Chapter 7
Expressions and Assignment Statements
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
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
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
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?
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
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)– *, /– +, -
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
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
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 likeif (count == 0)
average = 0
else
average = sum /count
Copyright © 2009 Addison-Wesley. All rights reserved. 1-95Copyright © 2009 Addison-Wesley. All rights reserved. 1-95
Arithmetic Expressions: Operand Evaluation Order
• Operand evaluation order1. Variables: fetch the value from memory2. 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
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);
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 problem1. 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
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
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
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
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
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
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
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
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 90 C Ada
.AND. and && and .OR. or || or
.NOT. not ! not
xor
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)
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 evaluationindex = 1;while (index <= length) && (LIST[index] != value)
index++;– When index=length, LIST [index] will cause an
indexing problem (assuming LIST has length -1 elements)
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)
Copyright © 2009 Addison-Wesley. All rights reserved. 1-109Copyright © 2009 Addison-Wesley. All rights reserved. 1-109
Assignment Statements
• The general syntax<target_var> <assign_operator> <expression>
• 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)
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
}
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
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
• Examplessum = ++count (count incremented, added to sum)
sum = count++ (count incremented, added to sum)
count++ (count incremented)-count++ (count incremented then negated)
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
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);
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
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
Thank Youfor
Your attention