Variable Declaration
Built-In Types in C++
Learn to declare variables using int, double, bool, and char: the fundamental building blocks of every C++ program.
What Is a Variable?
A variable is a named storage location in your computer's memory. Think of it as a labeled box: the label is the variable's name and the box holds a value you can read or change while your program runs.
Why Types Matter
C++ is a statically typed language: you must tell the compiler what kind of data a variable will hold before you use it. The type determines how much memory is reserved and what operations are allowed.
The Four Built-In Types
The Declaration Syntax
Declaration vs Initialization
You can declare a variable (create the box) without giving it a value right away. Initialization means assigning a value at the moment of declaration. Best practice: always initialize.
Deep Dive: int
The int type stores whole numbers (integers). On most systems, it uses 4 bytes (32 bits) and can hold values from roughly \(-2.1 \times 10^9\) to \(2.1 \times 10^9\).
Deep Dive: double
The double type stores decimal numbers using 8 bytes (64 bits) of floating-point precision. Use it whenever you need fractions, measurements, or scientific values.
Deep Dive: bool
A bool holds exactly one of two values: true or false. It uses 1 byte and is essential for conditions, loops, and decision-making in your programs.
Deep Dive: char
A char stores a single character using 1 byte. Characters must be enclosed in single quotes. Each character maps to a numeric ASCII code.
Memory Layout
Step-by-Step Checklist
Example 1: Student Profile
Declare variables to store a student's age, GPA, enrollment status, and first initial.
Example 2: Temperature Converter
Convert a temperature from Fahrenheit to Celsius using \( C = \frac{5}{9}(F - 32) \).
Example 3: Game State
Track a player's stats in a simple game with multiple variable types working together.
Common Mistakes
Type Comparison Table
| Property | int | double | bool | char |
|---|---|---|---|---|
| Size (bytes) | 4 | 8 | 1 | 1 |
| Stores | Whole numbers | Decimals | true / false | 1 character |
| Example | 42 | 3.14 | true | 'A' |
| Default Init | Undefined (if local) | Undefined (if local) | Undefined (if local) | Undefined (if local) |
| Arithmetic? | ✓ | ✓ | Limited | ✓ (ASCII) |
Question 1 of 5
Which type should you use to store the value 3.14159?
Question 2 of 5
What is the output of the expression \(7 / 2\) in C++ when both operands are int?
Question 3 of 5
Which declaration is valid C++?
Question 4 of 5
How many bytes of memory does a double typically use?
Question 5 of 5
What happens if you use a variable without initializing it?