Ready to practice?
Sign up to access interactive coding exercises and track your progress.
Back to C++ Programming Fundamentals
Lesson 7 of 15
Beginner
40 minutes
Variable assignment and initialization
Learn the difference between assignment and initialization, and how to work with variable values safely.
Prerequisites
Introduction to objects and variables
Not completed
Variable Assignment and Initialization
Assignment vs Initialization
Assignment
Gives a value to an already-existing variable:
int x; // Variable created but uninitialized
x = 5; // Assignment - gives x the value 5
Initialization
Gives a variable its initial value when it's created:
int x = 5; // Initialization - x gets value 5 when created
Types of Initialization
Copy Initialization
Uses the equals sign:
int x = 5;
double pi = 3.14159;
char grade = 'A';
Direct Initialization
Uses parentheses:
int x(5);
double pi(3.14159);
char grade('A');
Uniform Initialization (C++11)
Uses braces - preferred for new code:
int x{5};
double pi{3.14159};
char grade{'A'};
Multiple Assignment
You can assign the same value to multiple variables:
int a, b, c;
a = b = c = 10; // All three variables get value 10
Assignment Returns a Value
Assignment operations return the assigned value:
int x, y;
x = (y = 5); // y gets 5, then x gets 5
Best Practices
- Always initialize variables when you declare them
- Use uniform initialization
{}
when possible - Don't chain assignments unless necessary
- Initialize with meaningful values
Common Mistakes
// Bad - uninitialized variable
int count;
count = count + 1; // Undefined behavior!
// Good - properly initialized
int count = 0;
count = count + 1; // count is now 1
Variable assignment and initialization - Quiz
Test your understanding of the lesson.
7 questions
10 minutes
60% to pass
Practice Exercises
Variable Initialization vs Assignment
Learn the difference between initialization and assignment by working with variables.
Easy
3 hints available
Lesson Discussion
Share your thoughts and questions