Step 1 of 6
Your first variable
So far the program only printed fixed text. Real programs work with data that changes: scores, prices, names. To keep a piece of data around, you store it in a variable.
A variable is a named box in the computer's memory. In C, every box has a type that says what kind of value it can hold, and the type never changes. You create (declare) a variable by writing the type, then the name:
int kills = 25;
intis the type: a whole number (an integer) such as-3,0or25.killsis the name you'll use to refer to the box.= 25puts a starting value in it. This is called initializing the variable.
Printing a variable
printf can't print a number directly inside the quotes, because the text in quotes is fixed. Instead you put a format specifier where the value should appear, and give the value after the string. For an int the specifier is %d (for decimal):
#include <stdio.h>
int main(void) {
int kills = 25;
int rounds = 16;
printf("Kills: %d\n", kills);
printf("Rounds played: %d\n", rounds);
return 0;
}
Kills: 25
Rounds played: 16
Naming rules
Names can use letters, digits and underscores, but can't start with a digit, and can't be a C keyword like int or return. Names are case sensitive: score and Score are different variables. Pick names that say what the value means: total_price beats x.
Common mistakes
- Using a variable before declaring it: the compiler says
'score' undeclared. - Forgetting to initialize: a variable declared inside a function with no value, like
int score;, holds garbage (whatever was in that memory before) until you assign one. Using it before then is a bug the compiler often warns about. Always give variables a starting value.
Your turn: declare an int named score with the value 42.