4E. Abbreviations for Assignment Statements

Increment and decrement

It is very common to find that you want to change a variable by adding or subtracting 1. Of course,

  n = n + 1;
will change n to have a value one larger than its former value. But there are some convenient abbreviations. Statement
  n++;
means the same thing as n = n + 1; and statement
  n--;
is equivalent to statement n = n - 1;

Operator assignment

Statement

  x += E;
is equivalent to
  x = x + (E);
For example,
  kangaroo += 2;
is equivalent to
  kangaroo = kangaroo + 2;

You can use any binary operator (+, -, *, etc.) with =. For example, statement

  x *= n + 1;
has the same effect as statement
  x = x * (n+1);

x++ and x+1 are not the same

It is easy to confuse x++ with x+1. But the two have very different meanings: x++ changes the value of variable x, but x+1 does not change x.

Consider the following sequence of two statements.

  int n = 0;
  n+1;
What is the value of n after doing those statements? It must be n = 0. Recall that you can make any expression be a statement by adding a semicolon to it. Statement
  n+1;
means: compute the value of expression n+1, then ignore the value that you got. It does not change n. Evaluating n+1 never changes n, no matter what.

But statement

  n++;
does change n.

Two Standards

The coding standards for this course require the following.

  1. Only use abbreviations such as x++ and x-- as statements, not as expressions. Never write x++ as an argument of a function or as the right-hand side of an assignment statement.

  2. Do not write a statement that has no effect, such as

      x + 1;
    
    That serves no purpose and only confuses anyone reading the program.