- 4.1 Introduction
- 4.2 Control Structures
- 4.3 if Selection Statement
- 4.4 if...else Double-Selection Statement
- 4.5 while Repetition Statement
- 4.6 Counter-Controlled Repetition
- 4.7 Sentinel-Controlled Repetition
- 4.8 Nested Control Statements
- 4.9 Assignment Operators
- 4.10 Increment and Decrement Operators
- 4.11 (Optional) Software Engineering Case Study: Identifying Class Attributes in the ATM System
- 4.12 Wrap-Up
4.9 Assignment Operators
C++ provides several assignment operators for abbreviating assignment expressions. For example, the statement
c = c + 3;
can be abbreviated with the addition assignment operator += as
c += 3;
The += operator adds the value of the expression on the right of the operator to the value of the variable on the left of the operator and stores the result in the variable on the left of the operator. Any statement of the form
- variable = variable operator expression;
in which the same variable appears on both sides of the assignment operator and operator is one of the binary operators +, -, *, /, or % (or others we'll discuss later in the text), can be written in the form
- variable operator= expression;
Thus the assignment c += 3 adds 3 to c. Figure 4.15 shows the arithmetic assignment operators, sample expressions using these operators and explanations.
Fig. 4.15 Arithmetic assignment operators.
Assignment operator |
Sample expression |
Explanation |
Assigns |
Assume: int c = 3,d =5,e =4,f =6,g = 12; |
|||
+= |
c += 7 |
c = c + 7 |
10 to c |
-= |
d -= 4 |
d = d - 4 |
1 to d |
*= |
e *= 5 |
e = e * 5 |
20 to e |
/= |
f /= 3 |
f = f / 3 |
2 to f |
%= |
g %= 9 |
g = g % 9 |
3 to g |