

CS124 - Programming Language - Operators, Expressions and As
Presentation
•
Computers
•
University
•
Medium
Mara L
Used 22+ times
FREE Resource
32 Slides • 16 Questions
1
Operators, Expressions and Assignment Statements

2
Arithmetic Expressions
In programming languages, arithmetic expressions consist of operators, operands, parentheses, and function calls.
An operator can be:
•Unary – single operand
•Binary – two operands
•Ternary – three operands
Operators are described as:
•Infix – operators appear between operands
E.g. a + b; a and b are the operands, + is the operator
•Prefix - they precede their operands.
E.g. ++a;
3
Arithmetic Expressions:
Operator Evaluation Order
The operator precedence and associativity rules of a language dictate the order of evaluation of its operators.
The operator precedence rules for expression evaluation partially define the order in which the operators of different precedence levels are evaluated.
The operator precedence rules of the common imperative languages are nearly all the same because they are based on those of mathematics.
4
Multiple Choice
Operators that appear between operands.
Infix
Prefix
5
Multiple Choice
Which of the following is NOT found in an arithmetic expression?
Operators
Assignments
Function Calls
Operands
Parenthesis
6
Fill in the Blanks
Type answer...
7
Arithmetic Expressions:
Operator Evaluation Order
Many languages also include unary versions of addition and subtraction.
Unary addition is called identity operator (has no associated operation, meaning no effect to its operand.)
e.g. a + (- b) * c
In Java and C#, unary minus cause the implicit conversion of short and byte operands to int type.
In all of the common imperative languages, the unary minus operator can appear in an expression either at the beginning or anywhere inside the expression, as long as it is parenthesized to prevent it from being next to another operator.
e.g. a + - b * c //not legal expression
8
Most programming languages have a built-in implementation of exponentiation. Fortran, Ruby, Visual Basic, and Ada have the exponentiation operator - exponentiation has higher precedence than unary minus.
e.g. -(A ** B) is −AB
9
Arithmetic Expressions:
Associativity
Precedence accounts for only some of the rules for the order of operator evaluation; associativity rules also affect it.
Consider the following expression: a - b + c - d
If the addition and subtraction operators have the same level of precedence, as they do in programming languages, the precedence rules say nothing about the order of evaluation of the operators in this expression.
When an expression contains two adjacent occurrences of operators with the same level of precedence, the question of which operator is evaluated first is answered by the associativity rules of the language.
10
Multiple Choice
Among the operators, in Ruby, which is evaluated the highest priority?
** (exponentiation operator)
unary + and -
*, /, %
binary + and -
11
Multiple Choice
TRUE OR FALSE
When an expression contains two adjacent occurrences of operators with the same level of precedence, the question of which operator is evaluated first is answered by the associativity rules of the language.
True
False
12
Arithmetic Expressions:
Associativity
An operator can have either left or right associativity, meaning that when there are two adjacent operators with the same precedence, the left operator is evaluated first or the right operator is evaluated first, respectively.
Associativity in common languages is left to right, except that the exponentiation operator (when provided) sometimes associates right to left.
In the Java expression
a - b + c
the left operator is evaluated first.
13
Arithmetic Expressions:
Associativity
In Visual Basic, the exponentiation operator, ^, is left-associative.
The associativity rules for a few common languages are given here:
14
Arithmetic Expressions:
Parenthesis
Programmers can alter the precedence and associativity rules by placing parentheses in expressions. A parenthesized part of an expression has precedence over its adjacent unparenthesized parts.
For example, although multiplication has precedence over addition, in the expression
(A + B) * C
the addition will be evaluated first.
Languages that allow parentheses in arithmetic expressions could dispense with all precedence rules and simply associate all operators left to right or right to left.
15
Arithmetic Expressions:
Conditional Expressions
if-then-else statements can be used to perform a conditional expression assignment.
If (count == 0)
average = 0;
Else
average = sum / count;
In the C-based languages, this code can be specified more conveniently in an assignment statement using a conditional expression,
expression_1 ? expression_2 : expression_3
//If expression_1 evaluates to true, the value of the whole expression is the value of expression_2; otherwise, it is the value of expression_3.
//using the above example,
average = (count == 0) ? 0 : sum / count
16
Fill in the Blanks
Type answer...
17
Fill in the Blanks
Type answer...
18
Arithmetic Expressions:
Operand Evaluation Order
Side Effects
A side effect of a function, naturally called a functional side effect, occurs when the function changes either one of its parameters or a global variable.
a + fun(a) //If fun does not have the side effect of changing a, then the order of evaluation of the two operands, a and fun(a), has no effect on the value of the expression.
//However, if fun changes a, there is an effect. Suppose we have the following
a = 10;
b = a + fun(a);
Scenario 1: a is fetched first, then added to fun(a) -> result is 20
Scenario 2: fun(a) is evaluated first, then a is fetched -> result is 30
19
Fill in the Blanks
Type answer...
20
Arithmetic Expressions:
Operand Evaluation Order
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 of two-way parameters and non-local references
2.Write the language definition to demand that operand evaluation order be fixed
•Disadvantage: limits some compiler optimizations
Note that purely functional languages do not have this problem.
21
Arithmetic Expressions:
Operand Evaluation Order
Referential Transparency and Side Effects
Referential Transparency – a property whereby any two expressions that have the same value can be substituted for one another anywhere in the program without affecting the action of the program.
Example:
result1 = (fun(a) + b) / (fun(a) – c);
temp = fun(a);
result2 = (temp + b ) / (temp – c);
•Advantages:
1. Readability and reliability.
2. Programs can be reasoned about mathematically.
Note that purely functional languages have this property
22
Overloaded Operators
Use of an operator for more than one purpose is called operator overloading.
Common example: + for int and float addition
As an example of the possible dangers of overloading, consider the use of the ampersand (&) in C++. As a binary operator, it specifies a bitwise logical AND operation. As a unary operator, however, its meaning is totally different. As a unary operator with a variable as its operand, the expression value is the address of that variable.
Potential errors :
–Loss of compiler error detection (omission of an operand should be a detectable error)
–Some loss of readability
23
Multiple Choice
A property whereby any two expressions that have the same value can be substituted for one another anywhere in the program without affecting the action of the program.
Referential Transparency
Side Effect
Overloaded Operators
24
Multiple Choice
Using an operator for more than one purpose is called?
Side Effect
Operator Overloading
25
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
–In java:
•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 or int, or long
•double to byte, short, char or int, long, or float
26
Type Conversions
•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
–In java:
•byte to short, int, long, float, or double
•Note that even a widening conversion can be problematic.
–Consider a 32 bit int conversion to 32 bit float.
•The 9 decimal digits of precision for int converted to only seven decimal digits of precision of the float.
27
Type Conversions: Mixed Mode
•A mixed-mode expression is one that has operands of different types.
•A coercion is an implicit type conversion (when operands are of different data types)
•Disadvantage of coercions:
–A decrease in the ability of the compiler to detect “type errors”
•In most languages, all numeric types are coerced in expressions, using widening conversions.
–Java Example:
int a;
float b, c, d;
d = b * a; // Okay in java
•In Ada, there are virtually no coercions in expressions.
A : Integer;
B, C, D : Float;
C := B * A; Error in Ada
28
Multiple Choice
TRUE OR FALSE
In Java, coersion in acceptable using widening conversion.
True
False
29
Type Conversions: Explicit Type Conversions
In C language, Explicit type conversion is done by the user by using (type) operator. Before the conversion is performed, a runtime check is done to see if the destination type can hold the source value.
•Called casting in C-based language
•Examples
–C: (int) angle
–Ada: Float(sum)
Note that Ada’s syntax is similar to function calls
30
•Errors in the evaluation of expressions can occur in several cases.
–In cases of type coercions.
•If a languages requires type checking (ensuring that data has the appropriate type) then operand errors cannot occur.
–Inherent limitations of arithmetic
•division by zero in Math is not possible.
–Limitations of computer arithmetic
•Overflow or Underflow - when the result of an operation cannot be represented in the memory cell where it must be stored. depending on whether the result was too large (overflow) or too small (underflow).
–These types of exceptions can be ignored by the run-time system.
Some languages provide facilities for the detection and handling of these exceptions
31
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
• >, <, .GT., .LT., etc.
•JavaScript and PHP
–“7” == 7 vs. “7” === 7
•Ruby uses == for equality with coercions and eq1? For equality tests without coercions.
•Ruby uses === only in the when clause of its case statement
–In general, relational operators have lower precedence than the arithmetic operators.
•a + 1 > 2 * b
32
Relational and Boolean Expressions
•Boolean Expressions
–Operands are Boolean and the result is Boolean
–Example operators:
33
Relational and Boolean Expressions: No Boolean Type in C
•C 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:
•The left operator is evaluated, producing 0 or 1
–The evaluation result is then compared with the third operand (i.e., c)
•Consider: 8 < 7 < 1
34
Relational and Boolean Expressions:
•Some languages provide two sets of the binary logic operators.
•Perl and Ruby provide
two forms of AND
–&&
–and (has lower precedence than its && counterpart)
two forms of OR
–||
–or (has lower precedence than its || counterpart)
–Also, the precedence of && is higher than ||,
while the spelled out forms have equal precedence!
35
Multiple Choice
In Perl and Ruby, spelled out forms AND and OR have equal precedence as opposed to its precedence of && is higher than ||.
True
False
36
Multiple Choice
TRUE OR FALSE
In C language, it uses int type with 0 for false and nonzero for true as boolean values.
True
False
37
Relational and Boolean Expressions: Operator Precedence
38
Short Circuit Evaluation
•Short Circuit Evaluation - An expression in which the result can be determined without evaluating all of the operands and/or operators.
•Example: (13*a) * (b/13–1)
–If a is zero, the result will be 0, since 0 times any number is zero, so there is no need to evaluate (b/13-1)
–However, this type of shortcut is never taken since it cannot be detected very easily.
•Example: (a >= 0) && (b < 10)
If a is less than 0, making a >= 0 false, there is no need to evaluate (b <
10). This shortcut can be easily discovered during execution.
39
Short Circuit Evaluation
•Problem with languages that do not provide for non-short-circuit evaluation
index = 1;
while (index <= length) && (LIST[index] != value)
index++;
If a language provides short-circuit evaluation of Boolean expressions, then this is okay.
40
Short Circuit Evaluation
•Potential problem with languages that provide short-circuit evaluation and side-effects in expressions.
(a > b) || ( ( b++) / 3)
–These problems can be solved by providing additional operators that will cause full-evaluation of an expression to occur in all cases.
•Example the C-based languages use & and | for this purpose.
•Ada provides the two-word operators and then and or else to specify that short-circuit evaluation is to be used.
Index := 1;
While (Index <= Listlen) and then (List (Index) /= Key)
loop
Index := Index + 1;
end loop;
•All of the operators in Ruby and Perl are short-circuit.
41
Multiple Choice
A short circuit evaluation is an expression in which the result can be determined without evaluating all of the operands and/or operators.
To resolve programming languages that provide short circuit evaluation and side-effect in expression. In Ada, what keywords are used to specify that short-circuit is to be used?
IF THEN and OR ELSE
AND THEN and OR ELSE
42
Assignment Statements
•The general syntax
<target_var> <assign_operator> <expression>
•The assignment operator
The = in FORTRAN, BASIC, PL/I, C, C++, Java
The := in ALGOLs, Pascal, Ada
•Obviously, using = as the assignment operator and overloaded as the relational operator for equality can lead to many errors and therefore a bad design decision.
•Example: if (x = y) will not be detected as an error in this case.
•In the C-based languages the = operator can be embedded in expressions.
–a = b = c; is possible along with if ( a > (b = c) ) …
•Design choices have varied widely.
–Fortran and Ada require that an assignment can only appear as a stand-alone statement and the destination must be a single variable.
43
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
44
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){…}
– first the assignment statement
ch = getchar() is executed
(due to the parentheses)
–then the result (assigned to ch) is used as a conditional value for the while statement
•The disadvantage of allowing this type of side effect can hinder readability.
–Example: the previous expression must be read as a list of instructions…
–Example: a = b + (c = d / b++) -1;
45
Multiple Choice
What is the disadvantage of allowing to use assignment statement that produces a result, allowing the use of side effect as a conditional value?
reliability
readability
flexibility
none of the above
46
List Assignments
•Perl and Ruby provide multiple target, multiple-source assignment statements.
•Example in Perl:
–($first, $second, $third) = (20, 40, 60);
–($first, $second) = ($second, $first);
–Excess variables on the right-hand-side are ignored as in:
•($first, $second, $third) = (20, 40, 60, 70);
–Excess variables on the left-hand-side are set to undef as in:
–($first, $second, $third, $fourth) = (20, 40, 60);
47
Mixed-Mode Assignment
•Assignment statements can also be mixed-mode. That is the type of the (right-hand-side)rhs is not the same as that of the (left-hand-side)lhs.
•For example, the rules for the code below will depend upon the design decisions made for the particular language:
int a, b;
float c;
c = a / b;
•Fortran, C, C++ and Perl use coercion rules similar to those for mixed-mode expressions.
•In Pascal, integer variables can be assigned to real variables, but real variables cannot be assigned to integers.
•In Java and C#, only widening assignment coercions are done.
•In Ada, there is no assignment coercion.
•In Python and Ruby, types are associated with objects, not variables, so there is no such thing as mixed-mode assignment.
48
Fill in the Blanks
Type answer...
Operators, Expressions and Assignment Statements

Show answer
Auto Play
Slide 1 / 48
SLIDE
Similar Resources on Wayground
40 questions
Wk2 - Flowcharting_Sequential (ITCC105-101I)
Presentation
•
University
49 questions
Utility Program
Presentation
•
University
45 questions
Software
Presentation
•
Professional Development
41 questions
Scientific Method Lesson and Practice
Presentation
•
KG - University
43 questions
Introduction to STEM and Robotics Education
Presentation
•
University
44 questions
DCS2101 - Week 12 (Practical Applications 2)
Presentation
•
University
42 questions
Untitled Presentation
Presentation
•
University
41 questions
Image Formation
Presentation
•
University
Popular Resources on Wayground
20 questions
STAAR Review Quiz #3
Quiz
•
8th Grade
20 questions
Equivalent Fractions
Quiz
•
3rd Grade
6 questions
Marshmallow Farm Quiz
Quiz
•
2nd - 5th Grade
20 questions
Main Idea and Details
Quiz
•
5th Grade
20 questions
Context Clues
Quiz
•
6th Grade
20 questions
Inferences
Quiz
•
4th Grade
19 questions
Classifying Quadrilaterals
Quiz
•
3rd Grade
12 questions
What makes Nebraska's government unique?
Quiz
•
4th - 5th Grade