C Changing Variable Values
In this page:
Reassigning a Variable
A variable's value can be changed at any point after it's declared simply by assigning it a new value with the = operator, and the new value completely replaces whatever was stored there before.
Example: Reassigning a Variable
#include <stdio.h>
int main() {
int x = 5;
x = 10;
printf("%d", x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Changing Values with Arithmetic
A variable's value is often changed based on its own current value, such as adding to it, and C provides compound assignment operators like += and -= as a shorthand for reading, modifying, and storing back in one step.
Example: Changing Values with Arithmetic
#include <stdio.h>
int main() {
int total = 10;
total += 5;
printf("%d", total);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Copying One Variable's Value to Another
Assigning one variable's value to another copies that value at that specific moment; the two variables are then independent, and later changing one has no effect on the other.
Example: Copying One Variable's Value to Another
#include <stdio.h>
int main() {
int a = 5;
int b = a;
b = 10;
printf("%d %d", a, b);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Changing a Variable's Value in a Function
A function can only change a variable that belongs to its caller if it receives a pointer to that variable; without a pointer, the function only receives a copy and any changes are local to the function.
Example: Changing a Variable's Value in a Function
#include <stdio.h>
void increment(int *x) {
*x = *x + 1;
}
int main() {
int value = 5;
increment(&value);
printf("%d", value);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Constants Cannot Be Changed
A variable declared with the const qualifier can be initialized once but never reassigned afterward, and attempting to do so is a compile-time error, making const a way to guarantee a value stays fixed.
Example: Constants Cannot Be Changed
#include <stdio.h>
int main() {
const int MAX = 100;
printf("%d", MAX);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- C Introduction
- C History & Features
- C Environment Setup
- C First Program
- C Syntax & Structure
- C Statements
- C Comments
- C Keywords & Identifiers
- C Data Types
- C Character Data Type
- C Numeric Data Types
- C Decimal (Floating-Point) Numbers
- C sizeof Operator
- C Extended Data Types
- C Type Conversion
- C Booleans
- C Variables
- C Changing Variable Values
- C Multiple Variables
- C Constants
- C Fixed-Width Integers