We use the assignment operator to assign the result of the expression to the variable.
In the following example, we assign the integer value 10 to a variable score, the data type is integer.
int score = 10;
Suppose we have an integer variable and have orlautturinally assigned 10 to it.
And then we say we're going to increase the value by 5 and assign it a new value.
//declare and set value int x = 10; //increase the value by 5 and re-assign x = x + 5;
Another way to write the code "x = x + 5" is to use the shorthand assignment" + =", as follows.
//declare and set value int x = 10; //increase the value by 5 and re-assign x += 5;
The following is a list of shorthand assignment operators.
| Simple assignment | shorthand assignment |
|---|---|
| x = x + 1 | x + = 1 |
| x = x-1 | x-= 1 |
| x = x *(n + 1) | x * =(n + 1) |
| x = x /(n + 1) | x/=(n + 1) |
| x = x%y | x%= y |
In the following example, we get the value x,y from the user.
Then, we add y to x and assign the result to x.
Finally, we will print the new value stored in the variable x.
#include <stdio.h>
int main(void)
{
int x, y;
printf("Enter the value of x: ");
scanf("%d", &x);
printf("Enter the value of y: ");
scanf("%d", &y);
//add y to x and re-assign
x = x + y;
printf("New value of x: %d\n", x);
return 0;
}
Enter the value of x: 10 Enter the value of y: 20 New value of x: 30
another example using +=:
#include <stdio.h>
int main(void)
{
int x, y;
printf("Enter the value of x: ");
scanf("%d", &x);
printf("Enter the value of y: ");
scanf("%d", &y);
//add y to x and re-assign
x += y;
printf("New value of x: %d\n", x);
return 0;
}