What is a variable?
A variable is a named place in the computer's memory where you keep a value, so you can use it later.
Think of it like this: A variable is like a labelled box. The label is the name (
age), and inside the box is the value (25). In C every box also has a type: a box made for whole numbers can only hold whole numbers.
Creating a variable
To create a variable you write its type, its name, and a starting value:
#include <stdio.h>
int main() {
int age = 25;
printf("My age is %d\n", age);
return 0;
}Output
My age is 25
intis the type: a whole number (an integer).ageis the name we chose.= 25puts the value 25 into the box.
Printing a variable: %d
To print a variable, printf uses a placeholder. %d means "put a whole number here". After the text, add a comma and the variable. When the program runs, %d is replaced by the value.
You can have several placeholders. They are filled in order, left to right:
#include <stdio.h>
int main() {
int apples = 3;
int oranges = 5;
printf("%d apples and %d oranges\n", apples, oranges);
printf("Total: %d\n", apples + oranges);
return 0;
}Output
3 apples and 5 oranges Total: 8
Changing a variable
A variable can change – that's why it is called variable. Use = again to put a new value in. The old value is thrown away:
#include <stdio.h>
int main() {
int score = 10;
printf("Score: %d\n", score);
score = 50; // no "int" this time: the box already exists
printf("Score: %d\n", score);
score = score + 5; // take the old value, add 5, store it back
printf("Score: %d\n", score);
return 0;
}Output
Score: 10 Score: 50 Score: 55
Remember: You write the type (
int) only once, when you create the variable. After that you just use its name.
Common mistake: Using a variable before giving it a value.
int x; printf("%d", x);prints a random leftover number from memory. Always give your variables a starting value.