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;
}
Note: A variable name must be unique and cannot use a reserved keyword such as int or return. Names can contain letters, digits, and underscores, but they cannot start with a digit.

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

TypeStoresExample value
intWhole numbers42
floatDecimal numbers3.14
doubleLarger decimal numbers3.141592
charA single character'A'
Note: C is case sensitive, so myVar and myvar are two different variables. Pick a clear, consistent style for your names and stick with it.

Exercise: C Variables

What must you specify when declaring a variable in C?