Change Variable Values in C
Reassignment of Variables
In C, once a variable is declared, you can change its value any number of times during program execution.
When a new value is assigned, the old value is overwritten in memory.
Example
#include <stdio.h>
int main(void) {
int score = 50;
printf("Initial: %d\n", score);
score = 75; // reassign value
printf("Updated: %d\n", score);
return 0;
}
Output
Initial: 50 Updated: 75
Using Expressions for New Values
You can assign new values using calculations, function returns, or other variables.
This makes variables dynamic and useful in real-world logic.
Example
#include <stdio.h>
int main(void) {
int x = 5, y = 3;
x = x + y;
printf("x: %d\n", x);
return 0;
}
Output
x: 8
Compound Assignment & Increment/Decrement
C provides compound assignment operators that update a variable based on its current value, such as `+=`, `-=`, `*=`, `/=`, and the increment/decrement operators `++` and `--`.
Example
#include <stdio.h>
int main(void) {
int x = 5, y = 3;
x += y; // x = x + y -> 8
y *= 2; // y = y * 2 -> 6
x++; // x -> 9
y--; // y -> 5
printf("x=%d, y=%d\n", x, y);
return 0;
}
Output
x=9, y=5
Immutable Constants
Constants declared with `const` cannot change after initialization. Attempting to assign to a `const` variable is a compile-time error.
Example: `const int DAYS = 7; // cannot be reassigned`
Example
#include <stdio.h>
int main(void) {
const int DAYS = 7;
printf("DAYS=%d\n", DAYS);
// DAYS = 8; // error: assignment of read-only variable 'DAYS'
return 0;
}
Output
DAYS=7