Initialization vs.
Assignment
Master the fundamental difference between giving a variable its first value and changing it later: a concept that shapes how you write correct, efficient C++.
What Is a Variable?
A variable is a named region of memory that stores a value. Think of it as a labeled box: the label is the variable name, and whatever sits inside the box is the current value.
What Is Initialization?
Initialization is the act of giving a variable its first value at the moment it is created. The variable is born with a known state: no guessing, no garbage.
What Is Assignment?
Assignment is the act of replacing a variable's current value with a new one after the variable already exists. The old value is discarded.
The Lifecycle of a Value
The Core Rule
Three Forms of Initialization
Initialization vs. Assignment
| Feature | Initialization | Assignment |
|---|---|---|
| When | At declaration | After declaration |
| Type name present? | Yes | No |
| Previous value? | None (new variable) | Overwritten |
| Syntax options | =, (), {} | = only |
| Works with const? | Yes | No |
Why It Matters: const
A const variable can only be initialized, never assigned. If you forget to initialize it, the compiler will refuse to compile.
Why It Matters: References
A reference must be initialized when declared. It is permanently bound to the object it references and cannot be rebound later.
How to Apply This Knowledge
Example 1: Identify Each Line
Example 2: Uninitialized Variables
When you declare a local variable without initializing it, the memory is not zeroed out. The variable holds whatever garbage bits were left there by previous code. Reading it is undefined behavior.
Example 3: Class Objects
Common Mistakes
Summary at a Glance
| Scenario | Code | Init or Assign? |
|---|---|---|
| First value with = | int x = 5; | Initialization |
| First value with {} | int x{5}; | Initialization |
| Later change | x = 10; | Assignment |
| Const with value | const int k = 7; | Initialization |
| Const later | k = 8; // ERROR | Illegal |
| No value given | int x; | Uninitialized |
Question 1 of 5
Which line performs initialization?
Question 2 of 5
What will this code do?
Question 3 of 5
Which initialization form prevents narrowing conversions?
Question 4 of 5
After these two lines, what is the value of a?
Question 5 of 5
What is the best practice when declaring a local variable you intend to use immediately?