< previous page page_44 next page >

Page 44
LISTING 4.1 EVALUATING COMPLEX EXPRESSIONS

d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
1:     #include <iostream.h>
2:     int main()
3:     {
4:          int a=0, b=0, x=0, y=35;
5:          cout << a:  << a <<  b:  << b;
6:          cout <<  x:  << x <<  y:  << y << endl;
7:          a = 9;
8:          b = 7;
9:          y = x = a+b;
10:         cout << a:  << a <<  b:  << b;
11:         cout <<  x:  << x <<  y:  << y << endl;
12:         return 0;
13:     }

Output:
a: 0 b: 0 x: 0 y: 35
a: 9 b: 7 x: 16 y: 16
Analysis: On line 4, the four variables are declared and initialized. Their values are printed on lines 5 and 6. On line 7, a is assigned the value 9. On line 8, b is assigned the value 7. On line 9, the values of a and b are summed and the result is assigned to x. This expression (x = a+b) evaluates to a value (the sum of a+b), and that value is in turn assigned to y.
Operators
New Term: An operator is a symbol that causes the compiler to take an action.
Assignment Operator
New Term: The assignment operator (=) causes the operand on the left side of the assignment operator to have its value changed to the value on the right side of the assignment operator. The expression
x = a + b;
assigns the value that is the result of adding a and b to the operand x.
An operand that can legally 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.
Constants are r-values; they cannot be l-values. Thus, you can write
x = 35;              // ok

 
< previous page page_44 next page >

If you like this book, buy it!