C - Operator Compound Operator

Introduction

Consider the following statement:

number = number + 10;

there's a shorthand version:

number += 10;

The op in op= can be any of these arithmetic operators:

+  -  *  /  %

If we suppose number has the value 10, we can write the following statements:

number *= 3;               // number will be set to number*3 which is 30
number /= 3;               // number will be set to number/3 which is 3
number %= 3;               // number will be set to number%3 which is 1

The op in op= can also be in the following operators:

<<  >>  &  ^  |

Syntax

The general form of statements using op=:

lhs op= rhs;

where rhs represents any expression on the right-hand side of the op= operator.

The effect is the same as the following statement form:

lhs = lhs op (rhs);

Note the parentheses around the rhs expression. 

First, consider this statement:
variable *= 12;

This is the same as:

variable = variable * 12;

Because the op in op= applies to the result of evaluating the rhs expression, the statement:

a /= b + 1;

is the same as

a = a/(b + 1);

Related Topics