C Programming Assignment Operators

Last modified by Microchip on 2023/11/09 09:06

Assignment Statement
An assignment statement is a statement that assigns a value to a variable.

Simple Assignment

  • variable = expression;
  • The expression is evaluated and the result is assigned to the variable
OperatorOperationExampleResult
 Assignmentx = yAssign x the value of y

The simple assignment operator "=", assigns the value on its right to the variable on its left.

Back to top

Compound Assignment

  • variable = variable op expression;
  • Statements with the same variable on each side of the equals sign
  • May use the shortcut assignment operators (compound assignment)

Table 2

OperatorOperationExampleResult
+=Compound
Assignment
x += yx = x + y
-=Compound
Assignment
x -= yx = x - y
*=Compound
Assignment
x *= yx = x * y
/=Compound
Assignment
x /= yx = x / y
%=Compound
Assignment
x %= yx = x % y
&=Compound
Assignment
x &= yx = x & y
^=Compound
Assignment
x ^= yx = x ^ y
|=Compound
Assignment
x |= yx = x | y
«=Compound
Assignment
x <<= yx = x << y
»=Compound
Assignment
x >>= yx = x >> y

When writing any kind of program, there will be many instances where you will need to use a variable as part of an expression and you will want to assign the result of that expression into the same variable. An example of this kind of operation is when you want to increment a variable by some value (variable or constant). For example, if we wanted to add 5 to a variable called x, we could write it as x = x + 5 since we want to add 5 to the value of x and store the result back in x.

Back to top

Example

1
2
3
 x = x + 5;
// This operation may be thought of as:
//The new value of x will be set equal to the current value of x plus 5

Because it is extremely common to have the same variable on both sides of the expression, C provides a shortcut notation. This is implemented with one of a series of compound assignment operators. Using the same example, if we wanted to add 5 to the variable x, we could write it as x += 5. Similar operations may be carried out using one of the many compound operators shown in Table 2.

Back to top

Example

1
2
3
 x += 5;
//This operation may be thought of as:
//Increment x by 5

Back to top