Variables and Data Types in C++
Giving your program labelled boxes to remember things
- declare a variable with a type and a name,
- use the five everyday types
int,double,char,boolandstd::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.