Assignment Operators

The “assignment operator” (=) sets one value equal to another. The following statement assigns the value of sample to val:

val = sample;

Summary: You can combine an assignment with a bitwise or arithmetic operation.

In a convenient shorthand, C allows you to combine the assignment operator with any arithmetic or bitwise operator (see the “Arithmetic Operators” and “Bitwise Operators” sections). For example, the statement

val = val + sample;

can more conveniently be written

val += sample;

Both statements add val to sample and then assign the result to val.

Table 6.3 lists C's special assignment operators.

Table 6.3 Special Assignment Operators

Expression Equivalent Operation

x *= y x = x * y Multiplication
x /= y x = x / y Division
x %= y x = x % y Modulus
x += y x = x + y Addition
x –= y x = x – y Subtraction
x <<= y x = x << y Left shift
x >>= y x = x >> y Right shift
x &= y x = x & y AND
x ^= y x = x ^ y Exclusive OR
x |= y x = x | y Inclusive OR

Note that the equal sign always follows the other operator. In the following code,

val ^= sample;

val =^ sample;

the first statement is meaningful, but the second is a syntax error.