Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating Expressions and Statements 71

4



  • Assignment operators

  • Mathematical operators


Assignment Operators ......................................................................................


You saw the assignment operator (=) earlier. This operator causes the operand on the left
side of the assignment operator to have its value changed to the value of the expression
on the right side of the assignment operator. The expression
x = a + b;
assigns the value that is the result of adding aand bto the operand x.

l-values and r-values
An operand that legally can be on the left side of an assignment operator is called an
l-value. That which can be on the right side is called (you guessed it) an r-value.
You should note that all l-values are r-values, but not all r-values are l-values. An example
of an r-value that is not an l-value is a literal. Thus, you can write
x = 5;
but you cannot write
5 = x;
xcan be an l-value or an r-value, 5 can only be an r-value.

Mathematical Operators ..................................................................................


A second category of operators is the mathematical operators. Five mathematical opera-
tors are addition (+), subtraction (–), multiplication (*), division (/), and modulus (%).
Addition and subtraction work as you would expect: Two numbers separated by the plus
or minus sign are added or subtracted. Multiplication works in the same manner; how-
ever, the operator you use to do multiplication is an asterisk (*). Division is done using a
forward slash operator. The following are examples of expressions using each of these
operators. In each case, the result is assigned to the variable result. The comments to the
right show what the value of result would be

Constants are r-values. Because they cannot have their values changed, they
are not allowed to be on the left side of the assignment operator, which
means they can’t be l-values.

NOTE

Free download pdf