C - Variables
Variables name storage locations for values, with a declared type that determines the operations allowed and memory layout.
Learning Objectives
- Declare and initialize variables properly.
- Understand variable scope (global vs local).
- Recognize undefined behavior from uninitialized variables.
Prerequisites
Declaration and Initialization
#include <stdio.h>
int global_var = 100; // global scope
int main(void) {
int count = 3; // local, initialized
double pi = 3.1415; // local, initialized
char initial = 'A'; // local, initialized
int uninitialized; // dangerous! contains garbage
printf("%d %.2f %c\n", count, pi, initial);
// printf("%d", uninitialized); // undefined behavior!
}
Scope Examples
#include <stdio.h>
int global = 42;
int main(void) {
int local = 10;
{
int block_local = 5;
printf("In block: %d %d %d\n", global, local, block_local);
}
// block_local not accessible here
printf("Outside block: %d %d\n", global, local);
}
Common Pitfalls
- Using uninitialized variables leads to undefined behavior.
- Confusing assignment (
=
) with equality (==
). - Accessing variables outside their scope.
Checks for Understanding
- What happens if you use an uninitialized local variable?
- Where can a global variable be accessed?
- What format specifier prints an
int
?
Show answers
- Undefined behavior - it contains garbage values.
- Anywhere in the file after its declaration.
%d
Practice
- Declare variables for storing a person's age, height (in cm), and first initial.
- Explain why this is dangerous:
int x; printf("%d", x);