COS 333: Chapter 7, Part 2
Summary
TLDRThis lecture delves into expressions and assignment statements, covering relational and boolean expressions, short-circuit evaluation, and various assignment statements. It explains operator coercion in languages like JavaScript and PHP, the importance of distinguishing between equality and assignment, and the use of compound and unary assignment operators. The lecture also touches on the nuances of assignment expressions in different programming languages, the potential pitfalls of short-circuit evaluation, and the concept of mixed mode assignments, highlighting the need for understanding type coercion in programming.
Takeaways
- π The lecture focuses on expressions and assignment statements, building upon the concepts introduced in the previous lecture.
- π It discusses relational and boolean expressions, explaining how they define relationships or test for true/false conditions between operands.
- π The script highlights the difference in behavior between languages like JavaScript, PHP, and C++/Java in terms of operator coercion during equality and inequality checks.
- π It emphasizes the use of '===' and '!==' in JavaScript and PHP for strict equality and inequality checks without type coercion.
- π The concept of short-circuit evaluation is introduced, explaining how it can prevent unnecessary evaluation of operands in expressions.
- π‘ Potential issues arising from the lack of short-circuit evaluation are presented, such as accessing invalid array indices.
- π The lecture covers various programming languages' approaches to short-circuit evaluation, with some languages providing options for programmers.
- π Assignment statements are detailed, including the different operators and syntax used across languages, and the potential for ambiguity with the '=' operator.
- ππ Compound and unary assignment operators are explained, showing shorthand methods for incrementing or decrementing values.
- π The script touches on the precedence and associativity of unary assignment operators, which is important for understanding expression evaluation.
- ππ The use of assignment statements as expressions in some languages, like C, is highlighted, noting the potential for errors and side effects.
Q & A
What topics are covered in the second lecture on chapter seven?
-The second lecture on chapter seven covers relational and boolean expressions, short circuit evaluation, assignment statements, and mixed mode assignment.
What are relational expressions and what types of operators are included in this category?
-Relational expressions define some sort of relationship between two operands. They include equality and inequality expressions, as well as operators such as less than (<), less than or equal to (<=), greater than (>), and greater than or equal to (>=).
How does operator coercion affect equality and inequality checks in JavaScript and PHP?
-In JavaScript and PHP, operator coercion allows for the comparison of operands of different types by converting one operand to the type of the other, enabling the comparison to take place.
What is the difference between using triple equals (===) and double equals (==) in JavaScript for equality checks?
-The triple equals (===) performs an equality check without type coercion, comparing both value and type, while the double equals (==) performs the check with type coercion, meaning the operands may be converted to comparable types before comparison.
What is short circuit evaluation and why is it used?
-Short circuit evaluation allows an expression to produce a result without necessarily evaluating all operands and operators within the expression. It is used to prevent unnecessary evaluations, especially when the outcome of an expression can be determined without evaluating all parts.
What potential problems can arise if short-circuit evaluation is not supported in a programming language?
-If short-circuit evaluation is not supported, it may lead to runtime errors, exceptions, or invalid operations when attempting to evaluate operands that should have been skipped, potentially causing program termination or unexpected behavior.
How do different programming languages handle short circuit evaluation?
-Languages like C, C++, and Java have standard boolean operators that are short-circuit evaluated, while bitwise boolean operators are not. Languages such as Ruby, Perl, ML, F#, and Python have all of their logical operators short-circuit evaluated.
What is a conditional target in the context of assignment statements?
-A conditional target is a feature supported by some programming languages like Perl, where an assignment can be made to one of multiple targets based on a condition, using a ternary-like operator syntax.
What is the general syntax for an assignment statement and what is the purpose of the assignment operator?
-The general syntax for an assignment statement involves an assignment operator, a left operand (target variable), and a right operand (expression). The assignment operator is used to store the value of the expression in the target variable.
What are the problems associated with using assignment as an expression?
-Using assignment as an expression can reduce error detection capabilities, as a mistaken assignment operator may be used instead of a comparison operator. Additionally, it can cause side effects if the assignment changes the value of a variable that should not be altered in that context.
How do mixed mode assignments differ between languages like Java and C# compared to Fortran, C, and Perl?
-In Java and C#, only widening coercions are allowed in assignments, which is a safer approach as it prevents potential data loss due to narrowing coercions. In contrast, Fortran, C, and Perl allow any coercion, including narrowing, which can lead to data loss or unexpected results.
Why does Ada perform fewer coercions than most other high-level programming languages in assignments?
-Ada performs fewer coercions to ensure type safety and prevent potential data loss or unexpected behavior. It does not perform any assignment coercions, requiring explicit conversions when necessary.
Outlines
π Lecture Introduction to Expressions and Assignment Statements
This paragraph introduces the second lecture on chapter seven, focusing on expressions and assignment statements. It recaps the previous lecture's content on arithmetic expressions, overloaded operators, and type conversions. The lecture's agenda includes relational and boolean expressions, short circuit evaluation, assignment statements, and mixed mode assignments. Relational expressions are explained, highlighting their role in defining relationships between operands, such as equality and inequality. The paragraph also discusses operator coercion in languages like JavaScript and PHP, which allows for type conversion during equality or inequality checks.
π Deep Dive into Relational and Boolean Expressions
The second paragraph delves deeper into relational and boolean expressions, explaining how they work in different programming languages. It discusses the use of equality and inequality operators with and without coercion, using JavaScript, PHP, and Ruby as examples. The concept of short circuit evaluation is introduced, explaining how it can prevent unnecessary evaluation of operands in expressions, with an example of an arithmetic expression involving multiplication. Potential issues arising from the lack of short circuit evaluation are also highlighted, using an array iteration example that could lead to runtime errors if not properly handled.
β οΈ Potential Problems with Short Circuit Evaluation
This paragraph explores the potential problems that can arise from both the lack of support for short circuit evaluation and its misuse when side effects are expected within expressions. It provides examples of how short circuit evaluation can prevent unnecessary computation, but also how it can lead to issues if the programmer relies on side effects occurring every time an expression is evaluated. The paragraph discusses how different programming languages handle short circuit evaluation, with some supporting it for all logical operators and others providing options for both short-circuit and non-short-circuit evaluation.
π Understanding Assignment Statements and Their Varied Forms
The fourth paragraph discusses the general syntax and forms of assignment statements across different programming languages. It explains the use of assignment operators, the distinction between left and right operands, and how assignment can involve expressions. The paragraph also touches on the ambiguity that can arise from overloading the single equals operator for both assignment and relational equality tests, and how different languages address this issue, such as C-based languages introducing the double equals operator for relational comparisons.
π Advanced Assignment Concepts: Compound and Unary Operators
This paragraph examines advanced assignment concepts, including compound assignment operators that allow for shorthand incrementing or decrementing of values, and unary assignment operators that combine increment or decrement operations with an assignment. It explains the precedence and associativity of these operators, highlighting the difference between prefix and postfix increments and decrements, and their impact on the evaluation order in expressions.
π Assignment as Expression and Its Implications
The sixth paragraph discusses how assignment statements can also serve as expressions, which has implications for their use in conditions and loops. It explains that the result of an assignment is the value that has been assigned, allowing it to be used within other expressions. The paragraph also points out potential issues with this approach, such as reduced error detection capabilities and the risk of unintended side effects when assignments are used in conditions.
π Multi-target Assignments and Functional Programming Assignments
The final paragraph explores multi-target assignments, which allow for the simultaneous assignment of multiple values to multiple variables, and how this differs in functional programming languages. It demonstrates the power of single-step swap operations without intermediary variables and contrasts assignment operations in imperative and functional programming paradigms, highlighting the unique binding mechanisms in languages like ML and Haskell.
Mindmap
Keywords
π‘Expressions
π‘Assignment Statements
π‘Relational Operators
π‘Boolean Expressions
π‘Short Circuit Evaluation
π‘Operator Coercion
π‘Conditional (Ternary) Operator
π‘Compound Assignment Operators
π‘Unary Increment/Decrement Operators
π‘Mixed Mode Assignment
π‘Functional Programming
Highlights
Introduction to expressions and assignment statements, including arithmetic expressions, overloaded operators, and type conversions.
Discussion on relational and boolean expressions, and how they define relationships or boolean values between operands.
Exploration of short-circuit evaluation in expressions, which can prevent unnecessary operand evaluation.
Comparison of equality and inequality operators in JavaScript, PHP, and their behavior with type coercion.
Introduction of non-coercion comparison operators like triple equals and not equals equals in JavaScript and PHP.
Explanation of boolean expressions in C89, where int types are used with non-zero and zero values representing true and false, respectively.
Clarification of the left associative nature of boolean expressions and their evaluation from left to right.
Potential issues with short-circuit evaluation when it's not supported, leading to runtime errors or exceptions.
Overview of how different programming languages handle short-circuit evaluation with logical and bitwise operators.
Discussion on the problems that can arise with short-circuit evaluation when side effects are expected in expressions.
General syntax and forms of assignment statements, including the use of different assignment operators across languages.
Potential ambiguity issues with the single equals operator when used for both assignment and equality testing.
Introduction to compound assignment operators for incrementing or decrementing values, and their origin in Algol 68.
Explanation of unary assignment operators, including prefix and postfix increments and decrements.
Precedence and associativity of unary assignment operators, and how they differ from unary plus and minus operators.
Assignment statements producing a result in C-based languages, allowing assignments to be used within expressions.
Problems associated with using assignment as an expression, such as reduced error detection and potential side effects.
Support for multiple target multiple source assignments in languages like Perl, allowing for complex assignments in a single step.
Differences in assignment operations between functional and imperative programming languages, focusing on value binding.
Mixed mode assignments allowing different types of values to be assigned to variables, with different coercion rules across languages.
Safety in Java and C# with only widening coercions allowed in assignments, contrasting with more permissive languages.
Ada's strict approach to assignments with no coercions allowed, emphasizing language's focus on safety and correctness.
Transcripts
welcome to the second lecture on chapter
seven which deals with expressions and
assignment statements
in the previous lecture we introduced
the basic underlying concepts behind
expressions and assignment statements
we also spent a lot of time looking at
arithmetic expressions
then we took a brief look at overloaded
operators and finished off with type
conversions in this lecture we'll finish
the chapter wolf
these are the topics that we will be
looking at in today's lecture
we'll start off with a discussion on
relational and boolean expressions
then we'll look at short circuit
evaluation which applies to all types of
expressions including arithmetic
expressions and relational and boolean
expressions
then we'll look at the second main topic
covered in this chapter namely
assignment statements and we'll finish
off by looking at mixed mode assignment
which is similar to mixed mode
expressions which we discussed in the
previous lecture
now you should at this stage be very
familiar with relational expressions
which are expressions that define some
sort of relationship between two
operands
so with the in this category we include
equality and inequality expressions
which test respectively for two operands
being equivalent to one another or two
operands being not equivalent to one
another we also include expressions that
define some kind of inequality so this
would include then expressions with
operators such as less than less than or
equal to
greater than and greater than or equal
to
now in javascript and php we have the
equality
and inequality relational operators
which behave in a fairly similar fashion
to what you would expect in c plus or
java however the equality or inequality
check is performed with operator
coercion so what this means is that if
the types of the two operands don't
match then one of the operands will be
converted to the type of the other
operand so that the equality or
inequality comparison can take place
so that means that this kind of
expression would be valid here we are
testing for equality between the string
containing the single character seven
and the numeric value seven coercion
will take place here which means that
the two can then be compared to each
other and this will then produce a true
result
now if we want to perform a comparison
without coercion then we have the
relational operators triple equals
and not equals equals
and these will then perform the same
kind of operation as the equality and
inequality
operators respectively however no
operand coercion will take place so if
we perform then the same equality
comparison using the triple equals
operator
then
again we are comparing for equality the
string containing the character 7 and
the numeric value 7. this will then
produce a false result because the
operands are then not coerced to be
comparable to one another which means
that the comparison fails
now ruby has a similar kind of
arrangement to javascript and php
so it uses the double equals operator
for equality with coercions and then it
uses eql question mark for equality
without coercions
now boolean expressions are expressions
in which the operands must be boolean
and the result of the expression is also
a boolean value
so here we are talking about boolean as
a type as we discussed in the previous
chapter
now c89 the standardized version of c
has no boolean type
so it uses an int type for operands
within what would be interpreted as
boolean expressions
so a non-zero integer value is then
interpreted as true and a zero
value is interpreted as false and this
would be whenever one of these
expressions
is used as a condition for example for
an if statement or within a loop of some
sort
now boolean expressions then also
evaluate two integer values so a true
expression will evaluate to one and a
false expression will evaluate to zero
so one relatively odd result of this
design if you don't know how these
expressions work
is that it is legal for us to create an
expression such as a less than b
less than c
however this doesn't work as one would
expect it to work based on mathematics
so this in fact doesn't test to see
whether a is less than both b and c
and b is greater than a but less than c
and then c of course is greater than
both a and b
instead what happens is we evaluate
these operators from left to right
because they are left associative so
first of all we perform the comparison a
less than b now depending on what the
values of a and b are we will then
either get a zero value which indicates
a false or a one value which indicates a
true
so in other words this portion of the
expression evaluates to either zero or
one
the zero or one is then compared to c
and we test to see whether the zero one
is less than c or not and then that will
again produce a zero or one result
depending on whether that comparison
produces a true result or a false result
we'll now take a look at short circuit
evaluation so short circuit evaluation
allows an expression to produce a result
without necessarily evaluating all of
the operands and or operators within the
expression so let's look at this in
terms of a simple example which is an
arithmetic expression which you can see
over here
so this arithmetic expression uses a
multiplication operator and we have then
a left operand as well as a right
operand for that multiplication operator
so now let's assume that the value of
the variable a
is zero so in this case if we evaluate
our left operand we then have 13
multiplied by a which is 13 multiplied
by zero which of course produces a zero
result
now if we assume that multiplication is
a short circuit evaluated operator
what this means is we don't need to
evaluate the right operand and the
reason for this is that we know that
zero multiplied by any value produces a
zero result so because we've just seen
that the left operand
computes a zero result this means that
we have zero multiplied by something
which will produce a zero result meaning
we don't need to evaluate the entire
right operand
we also don't have to evaluate any of
the operators within the right operand
so this division and the subtraction do
not need to be evaluated
now there are potential problems that
can arise if short-circuit evaluation is
not supported within a programming
language so let's look at this in terms
of a fairly simple example
here we assume that we have an array
named list and list contains a number of
elements which is equivalent to
length
so here we have then some example code
we have an integer variable called index
and that is initiated to a value of zero
now we have a while loop and the
objective of this while loop is to
iterate through our list array one
element at a time we will stop iterating
either when we reach the end of our
array or if we find an element contained
in the array that is equivalent to value
which is the value that we are searching
for in the array
so
at each step we will then move one
element further along in the array so
let's look at the condition of our while
loop we have a logical and operator and
then we have a left operand and a right
operand
the left operand tests to see where the
index is still less than length so this
means that we are still within the
bounds of the array and as long as that
condition is true then we can still
continue searching
our write operand accesses our list
array at subscript index
and it compares this to
value so
the loop will then continue executing
when value has not been found in other
words the current value that we're
looking at in the list array is not
equivalent to the value that we are
searching for
now inside the body of our loop we then
just have an increment to index and this
moves us on then to the next position
within the list array
so now the question arises what if this
logical and operator over here is not
short circuit evaluated so what i would
like you to do at this point is to pause
the video and try to answer this
question
so if we assume that this logical and
operator is not short circuit evaluated
then let's assume that the value that we
are searching for is not contained at
all within our list array so we continue
iterating until eventually we reach the
end of our array and at this point index
is then incremented to one index
position past the end of our array in
other words index is incremented to
length so this is of course assuming
that our list array is indexed from zero
up to one and less than the length of
the array
so in this situation we will then get a
false result
for our left operand
however because we are assuming that our
logical and operator is not short
circuit evaluated we must then go on to
evaluate the right operand
so in this case we then attempt to
access our list array at subscript index
however index is equal to length so this
means this is an invalid array index now
of course what happens at this point
depends on the programming language that
we're working with there may in some
languages be a runtime error which will
terminate execution of the program
there may alternatively be an exception
that will be raised that we may be able
to catch or alternatively we may just
perform an invalid axis which will then
retrieve a value which may produce a
problem further along in runtime
now on the other hand if we assume that
our logical and operator is short
circuit evaluated then we know that we
can only produce a true result if both
the left and the right operands have a
value of true
so if we reach the end of the array we
know that our left
operand will then produce
a value of false and we therefore know
that the entire logical and operation
must then produce a result of false so
in that case it's been unnecessary for
us to evaluate the right operand and we
can then immediately conclude that the
condition for the while loop has become
false and we need to terminate execution
of the loop so this will then avoid the
problem that arises if the logical and
is not short circuit evaluated
now let's look at how a variety of
different programming languages deal
with short circuit evaluation
so c c plus plus and java have standard
boolean operators that are short
circuits evaluated and these include the
logical and and logical or operators
however the bitwise boolean operators
are not short circuits evaluated and
these include the bitwise and and
bitwise or operators
rubypel
mlfsharp and python have all of their
logic operators short circuit evaluated
now the added programming language again
provides a measure of flexibility to the
programmers the programmer can choose
whether they want short-circuit
evaluation or not
so there are non-short-circuit
and and all logical operators which are
represented by the special words and
and or
however there are then also short
circuit versions of the logical and and
or operators which are indicated by
means of the special words and then
and or else
two slides ago we discussed the fact
that a lack of support for short circuit
evaluation can cause potential problems
within a program
but it is equally possible for support
for short-circuit evaluation to also
cause potential problems and this will
occur if side effects are expected
within expressions so let's look at this
in terms of a simple example which is a
boolean expression over here
and here we are going to assume that the
logical or operator is a short-circuit
evaluated operator
now recall that a functional side effect
occurs when a function modifies either a
parameter or a global variable
so we discussed this back in chapter 15
earlier on in this course
so it's also possible for operators to
cause side effects and this will happen
when an operator changes one or more of
its operands
so what i would like you to do at this
point is to pause the video
and try to determine which operator in
our example causes a side effect
all right so if we look at our example
the only operator that causes a side
effect is this increment operator over
here because it changes the value of its
single operand namely the value of the
variable b
now if we rely on the fact that the side
effect must occur every time that the
expression is evaluated then when will
the side effect not occur so what i
would like you to do at this point is
again pause the video and try to answer
this question
all right so if we assume that our
logical or operator is short circuit
evaluated
then we will not evaluate our right
operand and in other words we will then
not evaluate this increment operator
which we've just determined does cause a
side effect
if we have a situation where the left
operand evaluates to true
and in this case we can then immediately
conclude that the entire logical
expression must then evaluate to true
because only one of the operands needs
to evaluate to true for the entire
logical or to be true so this means then
that we have no need to evaluate the
right operand and therefore we won't
perform the increment operation
now if we rely on the fact that we
expect that when this condition is
evaluated that b will always be
incremented then we have a problem
because when the logical or operator is
short-circuited this increment doesn't
take place
now we get on to the second major topic
for this chapter which is assignment
statements
so the general syntax for an assignment
statement involves an assignment
operator of some sort and then there are
two operands a left operand which must
be a target variable which we are
assigning to
and a right operand which is some sort
of expression the value of the
expression will then be stored in the
target variable
now the assignment operator can take
different forms so in fortran basic and
all of these c based languages a single
equals operator is used however in the
algol programming languages both algor
58 and alcohol 60 as well as pascal and
ada the colon equals operator is used
now we discussed all the way back in
chapter two where the codon equals
operator comes from it was originally
introduced in algol 58 and it comes from
an arrow notation that points from the
right hand side to the left-hand side
which is a mathematical notation
and it would have been represented as a
less than symbol followed by an equal
symbol which would look like an arrow
pointing from the right hand side to the
left hand side but due to character set
limitations a colon was used instead of
a less than symbol
now there is a potential problem that
arises if the single equals operator is
overloaded for use as the relational
equality operator which compares two
operands to each other and doesn't
perform an assignment
now this problem is an ambiguity between
the assignment
and equality test operations
so in order to solve this problem we
need separate operators for assignment
and for an equality test
so the c-based programming languages
solve this problem by introducing a new
operator
for relational comparisons of equality
and this is the double equals operator
which you should be familiar with
now this is potentially problematic
because a beginner programmer who isn't
familiar with the notation used in the
c-based programming languages may assume
that a single equals operator represents
a relational comparison for equality and
this may then cause confusion and
potential errors within the program code
which may be difficult to debug
now algol 58's
colon equals operator is unambiguous
because there is an entirely separate
way of representing assignment and
therefore a single equals operator can
be used for the relational equality
operation
conditional targets are supported in
perl and these are very similar in
format to the conditional expressions
that we spoke about in the last lecture
however conditional targets are used as
the target of an assignment operation
so this is the form of a conditional
target the conditional target being the
left operand of an assignment
so again we have three operands
and we have then operator symbols which
are the question mark and the colon
symbols
so
the operand then that appears to the
left of the question mark is a condition
in other words it must be a boolean
expression that evaluates to true or
false
now if this operand evaluates to true
then the entire conditional target
becomes the second operand which appears
between the question mark and the column
symbols
if however the first operand evaluates
to false then the entire conditional
expression becomes the third operand
which is
appearing to the right of the colon
symbol so what this means is in this
example if flag is true then zero is
assigned to total otherwise if flag is
false
then 0 is assigned to subtotal
so here we have then
an equivalent piece of code using an if
statement which performs the same
operation as our conditional target we
have an if which is then based on the
value of our flag
and if the flag is true then we assign 0
to total otherwise if the flag is false
then we assign 0 to subtotal
so what i would like you to do at this
point is to pause the video and try to
determine which of the programming
language evaluation criteria are
supported by support for conditional
targets within a programming language
now you should be very familiar with
compound assignment operators at this
point
which are a shorthand method for
specifying a very commonly used form of
assignment
namely an assignment that either
increments or decrements a value by a
user-specified amount
now compound assignment operators were
introduced in algol 68 and then later on
adopted by c and were therefore also
supported in all of the c based
programming languages
so over here we have an example of a
compound assignment
specifically one that performs an
incrementing operation
so the plus equals is the compound
assignment operator it has two operands
a lift operand which is the variable
that is being incremented and the right
operand which provides the value that we
should increment by so this is
equivalent to the longer form notation
which you see at the bottom over here
where we are assigning 2a
a's original value with b
added to it so we are essentially then
performing an increment to a
by the amount specified within the
variable b
now we also have a compound assignment
operator that performs a decrement
operation and in this case the operator
would be minus equals and this would
then be equivalent to an assignment
operation similar to what we see
for the compound assignment example that
we looked at before however instead of
performing an addition we would be
performing a subtraction operation
you should also be very familiar with
unary assignment operators which are
supported in all of these c-based
programming languages
these combine increments or decrement
operations with an assignment
so we'll consider
unary increment operators first and
there are two different variants of the
unary increments operator
namely a prefix increment sometimes
called a pre-increment and a post-fix
increment sometimes called a post
increment
so the prefix increment
is
an operator plus plus which appears
before the operand that it is applied to
namely count in this example
so the semantics for a prefix increment
are that we perform the increment and
then the incremented result is returned
so in this case we would increment count
by 1
and then the incremented value would be
returned and would be assigned to sum
now a postfix increment operator has the
same general form except that the
operator appears after the operand to
which it is applied namely count in this
example
so the semantics here
are that the result that is returned by
the increments operation is the original
value of the operand in this case the
value of count and then after this value
has been returned then the increment
operation is performed so in this case
the original unincremented value of
count will be assigned to sum and after
that assignment has taken place then the
increment is performed to counts value
now
the same applies to
unary decrement operators again there we
have a prefix decrement
and a postfix decrement and these have
exactly the same semantics as for the
prefix increments and postfix increment
except that a decrement operation is
performed instead of an increment
operation
so now we'll talk about precedence and
associativity of the unary assignment
operators what you should note here is
that this discussion is somewhat
different to what is presented in the
textbook where the textbook presents a
simplified view
so you should base your studying on what
is discussed in the slides here
so postfix increments and decrements are
at a higher precedence level than prefix
increment and decrement and the unary
plus and minus operators
so what this means is if these are mixed
then post fix increments and decrements
will be evaluated first before prefix
increments and decrements and unary plus
and minus operators
so postfix increment and decrement are
left to right associative we can see
that in this example over here where we
are applying the unary increment
and decrement postfix operators to count
so in this case the evaluation would be
that the increment is first applied to
count and then afterwards the decrement
is applied
so prefix
and unary increments and decrements are
at the same precedence level as unary
plus and minus unary plus and minus are
simply used to make value positive or
negative
now these operators are all right to
lift associative so over here we have an
example where we are performing a
negation as well as an increment to the
variable count
so in this case because we are
associating right to left we will first
perform
the pre-increment operation on count and
once that operation has completed then
we will negate the result
now in the c-based programming languages
as well as pull and javascript an
assignment statement actually produces a
result and that result is the value that
has been assigned
so if we consider this assignment over
here which is assigning a value of 4 to
a variable called number in this case
the value of the assignment will be 4
which is the value that has been
assigned to number
so what this means is that an assignment
can be used as an expression
and what this also implies is that an
assignment can then be used as an
operand within another expression
so here we have a fairly simple example
of this we have an if statement
and inside the condition of this if
statement we have a comparison operator
an equality comparison operator and an
assignment operator so the way that this
would be evaluated is that the
assignment would be performed first so
we would assign the value of the
variable c
to the variable b
and the result of that assignment would
then be c which is the value that has
been assigned
then we would compare a
to c
which is the result of the assignment
and we would test to see whether these
two are equivalent to one another this
would then produce either a true or a
false result
here we have another example of an
assignment that is used as an operand
and this is a very common use
of this kind of assignment particularly
in the c programming language so here we
have a while loop and the objective of
this loop is to read through an input
file one character at a time but we
don't know how many characters there are
contained in the files so we need to
stop once the end of the file is reached
now we know that a file end has been
reached once a special character is
encountered known as an endophile or eof
character
so in the condition of this while loop
we first have an assignment that takes
place
this assignment
calls the get char function which reads
a single character from the input file
and this character is then assigned to
the variable ch
so now ch contains the character that
has been read from the file and this can
be used in the body of our while loop
however this assignment also has a value
and the value of this assignment is the
character that has been read from the
file by means of the get char function
because this is the value that is
assigned
so this character value is then compared
by means of an inequality operator
to the eof character which is
represented by a named constant over
there
what this means is that the loop will
continue executing as long as the next
character that is read is not the end of
file character and as soon as the end of
file character is encountered then the
loop will end because we have fully
processed our file
now there are two problems associated
with using assignment as an expression
so first of all our error detection
capabilities are reduced
and this will occur in a situation where
we intend to type a double equals
equality comparison operator but instead
we must type this as a single equals
assignment operator
so in this example over here we have an
if statement and we have a condition and
this condition should have been x equals
equals y so in other words we wanted to
test whether x was equivalent to y
however instead of doing that we've
mistyped the double equals comparison
operator as a single equals assignment
operator
now because assignment is handled as an
expression this means that this
assignment returns a result which is
then y which is the value that has been
assigned
so this will then be the condition that
the if statement will base its decision
on
if we are working in c or c plus plus
then this will be interpreted on a
numeric level as either a true or a
false value
the second issue that can arise is that
an assignment can cause a side effect
so
in order to understand this we need to
recall that operators can cause side
effects by changing their operands
so if we look at this first example over
here
then what i would like you to do is
pause the video at this point and try to
explain how a side effect is caused in
this example
now pearl ruby and lewis support
multiple target multiple source
assignments
so here we have an example of such an
assignment
we have three targets in this case
namely first second and third all three
of which are variables we also have
multiple sources
the same number of sources as targets
and in this case our multiple sources
are 20 30 and 40. so the result of this
is that the value 20 will be assigned to
the variable first the value 30 will be
assigned to the variable second and the
value 40 will be assigned to the
variable third
now what's very interesting and what
illustrates the power of this kind of
assignment is that we can actually
perform a single step swap operation
without having to use an intermediary
variable to
hold a value during the assignment so
we've done exactly that in this example
over here
we are assigning the original value of
second to first and then the original
value of first to second
assignment in functional programming
languages works a little differently to
imperative programming languages so as
we've seen in chapter 15 in functional
languages identifiers are only names for
values they aren't actually variables
this means that we can't perform certain
kinds of operations like for example
incrementing a variable's value
so
in ml
names are bound to values using vel so
that's exactly what we've done here we
use the special word vel and we bind the
results of adding apples and oranges to
the name
fruit
so if another vowel then binds a
different value to fruit
following this initial binding then it
is a new name and the previous fruit is
hidden in that case
now if sharp uses lit instead of vowel
and this has a fairly similar result
again it's a binding of a value to a
name and it doesn't constitute a
variable
however lit also creates a new scope
which is not the case with vel in ml
finally we get to mixed mode assignments
so assignments just like expressions can
be mixed mode and again this is a
situation where the right and left
operands have different types so this
then allows us to assign a value of a
different type to the type of the
variable
so in fortran c c plus plus and perl
coercion rules will be applied to allow
these assignments to take place and this
happens for any numeric type value that
is assigned to any numeric type variable
so what i would like you to do at this
point is to pause the video and try to
explain what problem this can cause
in java and c-sharp only widening
coercions are allowed in assignments
in contrast within fortran c c plus and
perl
any coercion is allowed within an
assignment so these coercions may be
widening or narrowing coercions
so what i would like you to do at this
point is to pause the video and try to
explain why java and c sharp have a
safer approach in this regard
now ada once again performs fewer
coercions than most of the other
high-level computative programming
languages
and it performs no assignment coercions
at all
so what i would like you to do is again
pause the video at this point and
explain what this implies about ada's
assignments
all right so that concludes our
discussion on chapter seven
in the next lecture we will begin with
chapter eight in which we will discuss
statement level control structures
5.0 / 5 (0 votes)