Skip to main content

Section 3.12 Shortcut Operators

There are some operations that happen very frequently in programs. Adding 1 to a variable for example:
numberCorrect = numberCorrect + 1;
Because this operation is so common, C++ provides a shortcut for it. x += y; means โ€œincrease the current value of x by yโ€. So we could shorten the sample above to:
numberCorrect += 1;
It does not change the code at all, but it is a little easier to type. There are similar shortcuts for other arithmetic operations:
score -= 10;    // decrease the value of score by 10
score *= 2;     // double the value of score
score /= 3;     // divide the value of score by 3
Because adding one or subtracting one from a variable are so common, there is an even shorter way to express those operationsโ€”the ++ and -- operators. x++ means โ€œincrease the value of x by 1โ€ and x-- means โ€œdecrease the value of x by 1โ€. Here are some examples:
int numberCorrect = 0;
numberCorrect++;        // numberCorrect is now 1
numberCorrect++;        // numberCorrect is now 2
numberCorrect--;        // numberCorrect is now 1
To add one last wrinkle, you can also place ++ and -- before a variable.
int numberCorrect = 0;
++numberCorrect;        // numberCorrect is now 1
++numberCorrect;        // numberCorrect is now 2
--numberCorrect;        // numberCorrect is now 1
What is the difference? When ++ or -- is placed before the variable, the value of the variable is changed before the rest of the expression is evaluated. When ++ or -- is placed after the variable, the value of the variable is changed after the rest of the expression is evaluated. When used as the only operator in a statement, this does not matter. But in this example it does:
int x = 2;
int y = x++;  // y is 2, x is now 3 - x++ happened last
int z = ++x;  // z is 4, x is now 4 - ++x happened first

Warning 3.12.1.

++ and -- are easy to understand on their own. When combined with other operators, they can be confusing. Avoid using them in complex expressions. Focus on making your code clearly express what you want to doโ€”not on making it shorter. If you write y = x++ * 2; you are counting on others realizing that y will be set to 2 times the original value of x, not the new value of x. Writing y = x * 2; and then x++; on the next line does a better job of communicating your intent.
There is no reason you ever have to use the various shortcut operators. But you are going to see them in code written by others, so it is important to recognize what they do.

Checkpoint 3.12.1.

Checkpoint 3.12.2.

Checkpoint 3.12.3.

Checkpoint 3.12.4.

You have attempted of activities on this page.