- Understanding Data Types and Constants
- Working with Variables
- Working with Arithmetic Expressions
- Combining Operations with Assignment: The Assignment Operators
- Types _Complex and _Imaginary
- Exercises
Combining Operations with Assignment: The Assignment Operators
The C language permits you to join the arithmetic operators with the assignment operator using the following general format: op=
In this format, op is any of the arithmetic operators, including +, −, ×, /, and %. In addition, op can be any of the bit operators for shifting and masking, which is discussed later.
Consider this statement:
count += 10;
The effect of the so-called “plus equals” operator += is to add the expression on the right side of the operator to the expression on the left side of the operator and to store the result back into the variable on the left-hand side of the operator. So, the previous statement is equivalent to this statement:
count = count + 10;
The expression
counter -= 5
uses the “minus equals” assignment operator to subtract 5 from the value of counter and is equivalent to this expression:
counter = counter - 5
A slightly more involved expression is
a /= b + c
which divides a by whatever appears to the right of the equal sign—or by the sum of b and c—and stores the result in a. The addition is performed first because the addition operator has higher precedence than the assignment operator. In fact, all operators but the comma operator have higher precedence than the assignment operators, which all have the same precedence.
In this case, this expression is identical to the following:
a = a / (b + c)
The motivation for using assignment operators is threefold. First, the program statement becomes easier to write because what appears on the left side of the operator does not have to be repeated on the right side. Second, the resulting expression is usually easier to read. Third, the use of these operators can result in programs that execute more quickly because the compiler can sometimes generate less code to evaluate an expression.