Skip to main content

Variables and Initialization

beginner11 min readLesson 6 of 204

Types, declaration, initialization, assignment, and the brace-initialization habit that catches narrowing bugs.

A variable is a named piece of memory with a type. In C++, you declare it once and the compiler enforces the type forever:

int score = 0;            // whole numbers
double price = 19.99;     // floating point
char grade = 'A';         // a single character (single quotes!)
bool passed = true;       // true or false
std::string name = "Ha";  // text (double quotes) โ€” needs #include <string>

Declaration vs initialization vs assignment

  • Declaration creates the variable: int x;
  • Initialization gives it its first value โ€” do it on the same line, always.
  • Assignment replaces the value later: x = 5;

An uninitialized variable contains garbage. Not "zero", not "empty" โ€” garbage: whatever bits were already in that memory. Reading it is undefined behavior.

Brace initialization โ€” the modern default

int width{10};          // preferred modern form
int y = 3.7;            // compiles: y becomes 3 โ€” silently!
int z{3.7};             // error: narrowing conversion โ€” compiler catches it

Braces refuse lossy conversions. That is why this course writes {} for new variables: the compiler becomes your safety net.

auto โ€” say the type once

auto count = 10;        // int โ€” the compiler deduces it from the initializer
auto ratio = 0.5;       // double
auto title = std::string{"Report"};

auto is not a "dynamic type" (types are still fixed at compile time); it just avoids repeating them. Rule of thumb in this course: use explicit types for simple values, auto when the type is obvious from the right-hand side. (More in lesson 2C.)

Names matter

int x2tmp1; compiles; int pending_items; communicates. Modern C++ style: snake_case for variables and functions, PascalCase for types you will meet in module 10.

Practice next: declare, initialize, and compute โ€” the compiler will grade your types.

Now practice

Variables PracticeDeclare, initialize, convert โ€” including the brace-initialization narrowing check and swap-without-temp.1 challenge ยท ยท ~20 min