Sams Teach Yourself C++ in 21 Days

(singke) #1
This line is evaluated in the following order:
Add a to b.
Assign the result of the expression a + b to x.
Assign the result of the assignment expression x = a + b to y.

If a,b,x, and yare all integers, and if ahas the value 9 and bhas the value 7 , both xand
ywill be assigned the value 16. This is illustrated in Listing 4.1.

LISTING4.1 Evaluating Complex Expressions
1: #include <iostream>
2: int main()
3: {
4: using std::cout;
5: using std::endl;
6:
7: int a=0, b=0, x=0, y=35;
8: cout << “a: “ << a << “ b: “ << b;
9: cout << “ x: “ << x << “ y: “ << y << endl;
10: a = 9;
11: b = 7;
12: y = x = a+b;
13: cout << “a: “ << a << “ b: “ << b;
14: cout << “ x: “ << x << “ y: “ << y << endl;
15: return 0;
16: }

a: 0 b: 0 x: 0 y: 35
a: 9 b: 7 x: 16 y: 16
On line 7, the four variables are declared and initialized. Their values are printed
on lines 8 and 9. On line 10,ais assigned the value 9. On line 11,bis assigned
the value 7. On line 12, the values of aand bare 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. On lines 13 and 14, these results are confirmed by printing out the
values of the four variables.

Working with Operators ........................................................................................


An operator is a symbol that causes the compiler to take an action. Operators act on
operands, and in C++ any expression can be an operand. In C++, several categories of
operators exist. The first two categories of operators that you will learn about are

OUTPUT


70 Day 4


ANALYSIS
Free download pdf