Other Types of Assignment Operators

 

In addition to incrementing and decrementing a variable by one, it is common to increment/decrement by more than one.

int a = 1, b = 6;
a = a + 5;       // add 5 to a 
b = b - 4;       // subtract 4 from b
a = a + 1;       // add 1 to a

C++ has several operators that aid in these kinds of operations. These operators have the same precedence as the assignment operator, =. Assume:

int x = 8;

Operator

Example

Equivalent long form

Result

+=

x += 3

x = x + 3

11

-=

x -= 4

x = x - 4

4

*=

x *= 2

x = x * 2

16

/=

x /= 2

x = x / 2

4

%=

x %= 2

x = x % 2

0

The example above can be re-written as:

int a = 1, b = 6;
a += 5            // a is now 6
b -= 4;           // b is now 2
a += 1;           // a is now 7 (same as a++)
Previous slide
Next slide

Back to Lesson 9 Index
Back to Outline