Course contentsShow
← C
Lesson 73 of 1,2192. Variables and TypesFree lesson

What is a variable?

What is a variable?

What you'll learn: You will discover how C uses named containers to store and retrieve data in your computer's memory.

The Post-it Note Analogy

Imagine your computer's memory (RAM) is a massive wall of empty lockers. Each locker can hold a single piece of information, but there are millions of them, and they all look exactly the same. If you put a number in locker #482,901, you’ll probably forget where you put it by the time you need it again.

A variable is like putting a Post-it note label on one of those lockers. Instead of remembering a cryptic memory address, you give that space a friendly name, like playerScore or daysUntilVacation. When you tell C to look at playerScore, the computer automatically goes to the correct "locker," opens it, and reads the value inside.

A Name and a Value

In C, a variable consists of two main parts: the label (the name you choose) and the data (the value stored inside).

Think of a variable like a physical box. The name is written on the outside of the box, and the content is what you drop inside. Crucially, the content can change—hence the name "variable"—but the label stays the same. If your score goes from 10 to 20, you don't get a new box; you just reach inside, throw away the 10, and drop in a 20.

How it looks in code

To use a variable in C, you first have to introduce it to the compiler. This is called "declaring" the variable. You tell C what kind of data it holds and what its name is.

#include <stdio.h>

int main() {
    // We create a "box" that holds whole numbers (int) 
    // and label it "myLuckyNumber"
    int myLuckyNumber;

    // We put the value 7 inside that box
    myLuckyNumber = 7;

    // We can change the value later if we want
    myLuckyNumber = 13;

    return 0;
}

In the example above, myLuckyNumber is our variable. It acts as a placeholder. Anywhere we use that name later in our program, C will substitute it with whatever value is currently sitting inside that memory "locker."

Key takeaway

A variable is a named container in memory used to store, retrieve, and update information throughout your program.