← Back to C Course | Chapter 1: Introduction & Basics | Lesson 18 of 21

C Changing Variable Values

A variable's value can be reassigned at any time with =, modified based on its own current value with compound operators, or changed indirectly through a pointer passed to a function.

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

c
#include <stdio.h>
int main() {
	int x = 5;
	x = 10;
	printf("%d", x);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int total = 10;
	total += 5;
	printf("%d", total);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	int a = 5;
	int b = a;
	b = 10;
	printf("%d %d", a, b);
	return 0;
}

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

c
#include <stdio.h>
void increment(int *x) {
	*x = *x + 1;
}
int main() {
	int value = 5;
	increment(&value);
	printf("%d", value);
	return 0;
}

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

c
#include <stdio.h>
int main() {
	const int MAX = 100;
	printf("%d", MAX);
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.