C Variables
Variables are containers for storing data values, such as numbers and characters. In C, every variable has a type that tells the compiler how much memory to reserve and how to interpret the bits stored there. Getting comfortable with variables is the first real step toward writing useful C programs.
Creating Variables
In C you must declare a variable before you use it. A declaration states the type first, then the name, and optionally an initial value. This is different from languages like Python where you can just assign a value and go.
The general form is: type variableName = value; The type could be int for whole numbers, float or double for decimals, or char for a single character.
Declaring and using a variable
#include <stdio.h>
int main() {
int age = 25;
printf("I am %d years old.\n", age);
return 0;
}Declare First, Assign Later
You do not have to give a variable a value at the moment you declare it. You can declare it on one line and assign a value later. Just remember that reading a variable before you assign it gives you an unpredictable value.
Assigning a value after declaration
#include <stdio.h>
int main() {
int score;
score = 90;
printf("Your score is %d\n", score);
return 0;
}Changing and Reusing Values
Once a variable exists you can overwrite its value as many times as you like. The type stays the same, but the stored value can change during the program.
Overwriting a variable
#include <stdio.h>
int main() {
int count = 5;
count = 10;
printf("count is now %d\n", count);
return 0;
}Common variable types
Exercise: C Variables
What must you specify when declaring a variable in C?