Elementary Programming in C++: Augmented Assignment Operators, Increment and Decrement Operators

1. Augmented Assignment Operators

The operators +, -, *, /, and % can be combined with the assignment operator to form augmented operators.

Often, the current value of a variable is used, modified, and then reassigned back to the same variable. For example, the following statement increases the variable count by 1:

count = count + 1;

C++ allows you to combine assignment and addition operators using an augmented assign­ment operator. For example, the preceding statement can be written as follows:

count += 8;

The += is called the addition assignment operator. Other augmented operators are shown addition assignment operator in Table 2.3.

The augmented assignment operator is performed last after the other operators in the expression are evaluated. For example,

x /= 4 + 5.5 * 1.5;

is same as

x = x / (4 + 5.5 * 1.5);

x += 2; // Statement

cout << (x += 2); // Expression

2. Increment and Decrement Operators

The increment (++) and decrement (—) operators are for incrementing and decrementing a variable by 1.

The ++ and — are two shorthand operators for incrementing and decrementing a variable by 1. These are handy, because that’s often how much the value needs to be changed in many programming tasks. For example, the following code increments i by 1 and decrements j by 1.

int i = 3, j = 3;

i++; // i becomes 4

j–; // j becomes 2

i++ is pronounced as i plus plus and i– as i minus minus. These operators are known as postfix increment (postincrement) and postfix decrement (postdecrement), because the opera­tors ++ and — are placed after the variable. These operators can also be placed before the variable. For example,

int i = 3, j = 3;

++i; // i becomes 4

–j; // j becomes 2

++i increments i by 1 and —j decrements j by 1. These operators are known as prefix increment (preincrement) and prefix decrement (predecrement).

As you see, the effect of i++ and ++i or i– and –i are the same in the preceding examples. However, their effects are different when they are used in expressions. Table 2.4 describes their differences and gives examples.

In this case, i is incremented by 1, then the old value of i is used in the multiplication. So newNum becomes 100. If i++ is replaced by ++i as follows,

i is incremented by 1, and the new value of i is used in the multiplication. Thus newNum becomes 110.

Here is another example:

double x = 1.1;

double y = 5.4;

double z = x–– + (++y);

After all three lines are executed, x becomes 0.1, y becomes 6.4, and z becomes 7.5

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *