Expressions and Assignments
Fundamentals of Programming
Languages
Flow Control
! Sequence of Execution
" Within an Expression
# Functions that evaluate data objects and return a value
" Among program Statements
# Complete syntactic unit or sentence
" Between program Units
# Different Reference Environments
# Single in/out points (data stored on stacks)
Expressions
! Fundamental means of specifying computations in a programming language
! Motivation behind programming languages
! Arithmetic Expressions
" Return a numeric value
! Predicate Expressions
" Return TRUE or FALSE
! Postfix, Infix and Prefix Expressions Styles
Arithmetic Expressions
! Key Issues to Understand
" What are Operators?
" Operator Precedence Rules
" Operator Associativity Rules
" Order of Operand Evaluation
" Restrictions on operand evaluation side effects
" User-defined operator overloading
" Mode mixing in expressions
Arithmetic Expressions
! Operators
" Evaluate operands and return a single value
" Unary – single operand
" Binary – two operands
" Ternary – three operands
result = (count == 0) ? sum : sum /
count;
! Operator Precedence Rules
" Defines the order in which adjacent operators of
different precedence level are evaluated.
" Operators are adjacent of they are separated by at
most one operand
Arithmetic Expressions
! The Usual Precedence Levels:()
Unary operators --, ++, new, delete, cast, not, *, dereference
Exponentiation ** or ^
Unary +, -
*, /, %
+, -
Shift operators <<< >>> <<= >>=
Inequality comparisons <, <=, >, >=
Equality Comparisons ==, !=
AND
OR
throw exception
comma
! Operator Associativity
" order in which adjacent operators of the same
precedence level are evaluated.
! Typical Associativity Rules
" Left to right evaluation for binary operators
# Except exponentiation (**) which is right to left
# Except prefix ++, -- and unary +, -
" Unary operators associate right to left
! Precedence and Associativity can be
overridden with parenthesis.
Arithmetic Expressions
Arithmetic Expressions
! Operand Evaluation Order
" Variables
# Fetch the value from memory
" Constants
# Fetch the value from memory
# Can be included in machine code instruction (+1)
" Parenthesized Expressions
# Evaluate enclosed operands and operators first
" Function References
# Hmmmmm? Very interesting……
Arithmetic Expressions
! Side Effects of Evaluation Order - Functions" Function changes a two-way parameter
(reference)" Function changes a global variable" Function used in an expression alters another
operand used in the expression." Compute the result of the expression:
int fun(int &a){return a=a * 3;}main(){
int b = 6;
int c = b + fun(b);}
Arithmetic Expressions
! Solutions are in language definitions:
" Disallow functional side effects
# No two-way parameters in functions
# No nonlocal references in functions
# This is very restrictive to programmers
" Demand operand evaluation order be fixed
# Limits compiler optimizations
# C - functions always evaluated first
Arithmetic Expressions
! Side Effects of Evaluation Order - Overflow
" Assume integer range of:
–32,678 to 32,676
" Compute the result of the expression
25,000 + 20,000 – 15,000
" Left to right evaluation results in overflow
" Right to left evaluation gives correct value
Arithmetic Expressions
! Operator Overloading
" The operation executed by the operator symbol
is dependent on the operands (type, number,
etc.)
" Examples:
# Integer addition
int + int
# Floating point addition
float + float
# String concatenation
string + string
Arithmetic Expressions
! Operator Overloading
" Reduces compiler ability to perform error checking.
" Loss of readability
" Avoid need to overload by introducing new symbols
# div for integer division in Pascal
" User-defined overloading decreases readability
farther, but provides tremendous programming
flexibility.
Type Conversions
! Narrowing Conversion" Converts an object to one that cannot include all of
the values of the original type. (float to int)
! Widening Conversion" Converts an object into a type that can include all of
the values of the original types. (int to float)
! Mixed-Mode Expression" Expression with operand of different types
! Coercion" An implicit type conversion
! Cast" An explicit type conversion
Type Conversions
! Decreases compiler type error detection ability
! Numeric types are frequently coerced in expressions using widening.
! Avoid coercion – use casting
" Increased reliability and readability
Predicate Expressions
! Relational Expressions
" Relate or compare two objects (data items)
" Returns a Boolean value (true/false)
" Operator symbols can vary:
not equal to: !=, /=, .NE., <>, #
" Side Effects:
# A legal expresion in C:
A < B < C
# Evaluates as:
(A < B) is true or false so we get
true < C or false < C
Predicate Expressions
! Boolean Expressions
" Operands are Booleans
" Result is Boolean
" ‘C’ has no Boolean type
# Uses int
# FALSE is zero
# TRUE is non-zero
Short Circuit Evaluation
! Terminating the evaluation of an expression as soon as the result can be determined.
! Boolean Expressions
(a >= 0) and (c < b)
! C, C++, and Java:
" use short-circuit evaluation for Boolean
operators (&& and ||)
" provide bitwise Boolean operators that are not
short circuit (& and |)
Short Circuit Evaluation
! Important in loop control evaluation.
" Prevents index overflow
" But – AND & OR usually have low precedence
! Can expose side effects in code:
(a > b) || (b++ / 3)
Short Circuit Evaluation
" Search through an array list[] to find key
int list[maxIndex];
i = 0; . . .
while ((i < maxIndex) && (list[i]<>key))
{ i = i + 1; }
! Linked list with zero or one node: if (head==NULL || head.getNext()==NULL)
versus
if (head.getNext()==NULL || head==NULL)
Assignment Statements
! Operator Symbol
" FORTRAN, BASIC, PL/I, C, C++, Java
=" ALGOLs, Pascal, Ada
:=
" PL/I also uses = for relational equality
A = B = C;
Assignment Statements
! Multiple Targets (PL/I)
a, b = 10;
! Compound Assignment Operators (C, C++, Java)
sum += next;
! Unary Assignment Operators (C, C++, Java)
a++;
! Arithmetic Binary Operator (C, C++, Java)
a = b * (c = d * 2 + 1) + 1
! Conditional Targets (C, C++, Java)
(first == true) ? total : subtotal = 0
Assignment Statements
" Assignment as an expression
" In C, C++, and Java,
# assignment statement produces a result
# can be used as operands in an expression
while ((ch = getchar() != EOF) { ... }
" Has wicked-bad & extremely evil expression side effectint x = 4;
if ( x = 2)
cout << “x is 2!”;
else
cout << “x is not 2!”;
Assignment Statements
! Mixed-Mode Assignment
int = float
" In FORTRAN, C, and C++, # any numeric value can be assigned to any numeric scalar
variable; whatever conversion is necessary is done
" In Pascal, # integers can be assigned to reals, but reals cannot be
assigned to integers (the programmer must specify whether the conversion from real to integer is truncated or rounded)
" In Java, # only widening assignment coercions are done
" In Ada, # there is no assignment coercion