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:
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
Warning3.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.