As the name suggests, the simple assignment operator = is used to assign a value. Unlike in mathematics, this operator does not test for equality!
In the simplest case, simple assignment can be seen as variable initialization:
variable = value;
Write a program that prints Tamara's programming grade (5) and Vlada's long jump record (5.15m):
#include <stdio.h>
int main(void)
{
int t = 5;
double v = 5.15;
printf("%d\n%lg", t, v);
return 0;
}
The standard output produces:
5 5.15
In general, assignment can be understood as:
variable = expression;
First, the expression on the right-hand side is evaluated, and the result is stored in the variable on the left-hand side. Tamara got $10 from her grandparents and $10 from her parents, while Vlada got $5 from his brother, $5 from his aunt and $10 from his parents:
#include <stdio.h>
int main(void)
{
int t = 10 + 10;
int v = 5 + 5 + 10;
printf("%d\n%d", t, v);
return 0;
}
20 20
The expression can also contain variables:
#include <stdio.h>
int main(void)
{
int t1 = 10, t2 = 10;
int t = t1 + t2;
int v1 = 5, v2 = 5, v3 = 10;
int v = v1 + v2 + v3;
printf("%d\n%d", t, v);
return 0;
}
If the variable on the left had a previous value, that value is overwritten. Vlada's personal best was 4.9m, but today he jumped 5.15m:
#include <stdio.h>
int main(void)
{
double v = 4.9;
printf("%lg\n", v);
v = 5.15;
printf("%lg", v);
return 0;
}
4.9 5.15
By assigning a new value, the previous value is overwritten and permanently replaced.