In mathematics, the equal (=
) sign is a symbol that represents equality between two parts. In
computer science, the equal operator has a different meaning: assignment. That is to say
that the right part of the operator will be assigned to the left part which is necessarily a variable.
x = a + b;
In the example above, the result of the calculation a + b
will be assigned to the variable x
. To clarify
this concept of assignment, let's study the a = a + 1
from the mathematical and computer science point of view:
In the case of a mathematical equation, this is a relationship that can be simplified:
$$ \begin{align} a &= a+1 \\ \cancel{a} &= \cancel{a}+1 \\ 0 &= 1 \end{align} $$
This relationship is always false since 0 ≠ 1.
In C, the statement a = a + 1;
means that the new value of the variable a
will be equal to the old value plus one.
We would represent this relation in the following mathematical form:
$$ a_{n+1} = a_n + 1 $$
In C, we frequently use instructions of the type i = i + 2;
where the variable
which is assigned the final value is also used in the calculation. There is a
short notation i += 2
which is equivalent to i = i + 2;
.
We introduce here a new assignment operator +=
which sums the two operands
before assigning the result to the left operand. Here is an example:
int x = 3;
// Here the value of x is 3
x += 7;
// Now x is 10 (3+7)
These combined operators allow to simplify operations such as adding a value to a variable and storing the result. Here is the list of assignment operators with their equivalent instruction :
Operator | Example | Same as |
---|---|---|
+= |
a += b; |
a = a + b; |
-= |
a -= b; |
a = a - b; |
*= |
a *= b; |
a = a * b; |
/= |
a /= b; |
a = a / b; |
%= |
a %= b; |
a = a % b; |
&= |
a &= b; |
a = a & b; |
|= |
a |= b; |
a = a | b; |
^= |
a ^= b; |
a = a ^ b; |
<<= |
a <<= b; |
a = a << b; |
>>= |
a >>= b; |
a = a >> b; |
Consider the following example:
int a = 18;
// Division combined operator
a /= 3;
printf ("a = %d\n", a );
In the following code, modify each operation in order to use combined operators:
int x1=4, x2=2, x3=6;
// USE COMBINED OPERATORS (+=, -=, *= ...)
x1 = 2 + x1;
x1 = x1 * x2;
x2 = x2 % (1+x1);
x3 = x3 / x2;
// Display the results
printf ("x1= %d\n", x1);
printf ("x2= %d\n", x2);
printf ("x3= %d\n", x3);
The result must obviously be the same:
x1 = 12
x2 = 2
x3 = 3
What does the following program display?
int x=3;
x += 2;
printf ("%d", x );
x = x +2;
.
Try again...
What does the following program display?
float x=10.0;
x /= 3.0;
printf ("%f", x );
x = x / 3.0;
Try again...
What is the equivalent instruction with a combined operator?
x = 12 % x;
%
, otherwise it is not possible (like here).
Try again...
What is the equivalent instruction with a combined operator?
x = x % 12;
x
is to the left of the operator %
.
Try again...