Lesson 8: Variable Declaration and Initialization
Declaration
Declaring a variable tells the compiler three things:
- The name of the variable.
- The type of data it will store.
- The amount of memory to reserve.
Syntax: data_type variable_name;
c int age; double salary; char initial;
Initialization
Initialization is the process of assigning an initial value to a variable.
Syntax: data_type variable_name = value;
c int count = 0; double price = 19.99; char status = 'R';
You can declare multiple variables of the same type in one statement: c int x, y, z = 50;
Local vs. Global Variables (Preview)
- Local Variables: Declared inside a function. They are not initialized automatically and contain garbage values until explicitly assigned.
- Global Variables: Declared outside all functions. They are automatically initialized to zero (0 for numeric types,
NULLfor pointers).
Best Practice: Always initialize local variables to prevent unpredictable behavior caused by garbage data.