C Programming Assignment Operators
Simple Assignment
- variable = expression;
- The expression is evaluated and the result is assigned to the variable
Operator | Operation | Example | Result |
---|---|---|---|
Assignment | x = y | Assign x the value of y |
The simple assignment operator "=", assigns the value on its right to the variable on its left.
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
Operator | Operation | Example | Result |
---|---|---|---|
+= | Compound Assignment | x += y | x = x + y |
-= | Compound Assignment | x -= y | x = x - y |
*= | Compound Assignment | x *= y | x = x * y |
/= | Compound Assignment | x /= y | x = x / y |
%= | Compound Assignment | x %= y | x = x % y |
&= | Compound Assignment | x &= y | x = x & y |
^= | Compound Assignment | x ^= y | x = x ^ y |
|= | Compound Assignment | x |= y | x = x | y |
«= | Compound Assignment | x <<= y | x = x << y |
»= | Compound Assignment | x >>= y | x = 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.
Example
2
3
// 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.
Example
2
3
//This operation may be thought of as:
//Increment x by 5