Lesson 24 +10 XP

Variable Declaration and Assignment

Variable Declaration and Assignment

Now that we have variables, let's put values in them. There are two different ways: declaration and assignment.

Declaration

Declaration creates the variable. After this line, x exists but has no guaranteed value:

int x;

Assignment

Assignment copies a value into a variable after it already exists:

int x;     // created, but empty
x = 5;     // assignment: copy 5 into x
x = 7;     // assignment: now x holds 7

Declaration with initialization

You can do both at once:

int x = 5;

The variable is created and given the value 5 in the same statement.

The danger of uninitialized variables

An uninitialized local variable holds a garbage value - whatever bits happened to be in that memory. Reading it is undefined behavior. Always initialize:

int x = 0;   // safe

TL;DR

  • Declaration creates a variable: int x;.
  • Assignment stores a value into it: x = 5;.
  • Initialize at creation to avoid garbage values: int x = 0;.
  • Reading uninitialized variables is undefined behavior.