Wednesday, September 30, 2015

SOFT6008 Assignment Statement Review

Some students in the class are struggling with assignment statements and expressions

An assignment states changes the value of the variable (left of the equals sign) to the value of the expression (on the right if the equals sign)

Suppose the variable
a holds 20 and
b holds 15


Consider the following statement

a = b + 4;

This asks the computer to calculate the value of (b + 4), which is 19, and put it into the variable a.

So after this statement is executed
a holds 19 and
b holds 15

Note that using b in an expression on the right of the equals does not cause be to be altered.

Only the variable on the left of the equals is changed.



x - 20 is an expression
It will evaluate to something depending on the value of x
It does not DO anything. No variables are ever altered by an expression.

y = x - 20
This statement takes whatever is in x, subtracts 20 from it, and puts the answer into y.
x remains unchanged



Shorthand

There are shorthand assignments that can also be used and these are popular with many programmers

x += y is the same as x = x + y
x++ is the same as x = x + 1
x -- is the same as x = x - 1

However you may chose to stick to the long form in order to avoid confusion


No comments: