Variables, Declaration & Assignment
beginner10 min readLesson 4 of 148
A variable is a named box of memory. Declaration creates it, assignment replaces its content, initialization does both at once.
Boxes with names
A variable is a named region of memory holding a value of one type.
int score; // declaration: box exists, content UNSET
score = 42; // assignment: put 42 in the box
int lives = 3; // declaration + initialization together
Reading an uninitialized variable is undefined behavior. The compiler may warn; the program may print garbage. Rule: initialize on declaration whenever you can.
Assignment replaces
int x = 1;
x = 2; // x is now 2; the 1 is gone
x = x + 5; // right side computed first: 2 + 5 = 7
x += 5; // shorthand for x = x + 5
Assignment is not equality โ it is a command: "evaluate the right side, store it into the left side".
Multiple variables
int a = 1, b = 2; // legal but style prefers one per line