The op= Form of Assignment - C Operator

C examples for Operator:Compound Operator

Introduction

Consider the following statement:

number = number + 10;

This sort of assignment has a shorthand version:

number += 10;

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

+  -  *  /  %

If you suppose number has the value 10, you 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 a few other operators.

<<  >>  &  ^  |

The op= set of operators always works the same way.

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);

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 Tutorials