Skip to content

Variables and Data Types in C++

Programming C++ Difficulty 1/5

Beginning of the lesson

Variables and Data Types in C++

Giving your program labelled boxes to remember things

Big Idea: A variable is a named box in the computer's memory where your program keeps a value. In C++ every box has a type that says what kind of value it holds — a whole number, a decimal, a single letter, a yes/no, or some text.
By the end you will be able to:
  • declare a variable with a type and a name,
  • use the five everyday types int, double, char, bool and std::string,
  • explain why C++ needs the type written up front,
  • give a variable a starting value (initialization).

1. What is a variable?

Think of your computer's memory as a big shelf full of boxes. A variable is one box that you give a name so you can find it again, and inside it you store a value.

The name lets you read the value back or change it later. Here is the smallest useful example — one box called score holding the number 10:

#include <iostream>

int main() {
    int score = 10;
    std::cout << "Score: " << score << "\n";
    return 0;
}

Output:

Score: 10

int score = 10; reads as: "make an int box named score and put 10 in it." std::cout then prints what is inside.

2. Why C++ wants the type up front

Every box needs a type written before its name. The type is a promise about what will live inside. C++ is a statically typed language: you tell it the type once, at declaration, and it stays that type.

Why bother? Two big reasons:

  • Size & shape. The computer needs to know how much memory to set aside. A whole number, a letter, and a decimal are stored differently.
  • Safety. If you promise a box holds a whole number, the compiler can warn you before the program runs if you try to misuse it. Mistakes are caught early.
Memory (RAM) name · value · type age price grade 12 4.99 'A' int double char
Each variable is a labelled box: a name, a value inside it, and a type that says what kind of value.
An analogy: variables are like labelled jars in a kitchen. The label (type) says "sugar only" or "salt only". You would not pour soup into the sugar jar — and C++ helps you keep each jar for its own kind of thing.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers