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

  1. What happens if you use an uninitialized local variable?
  2. Where can a global variable be accessed?
  3. What format specifier prints an int?
Show answers
  1. Undefined behavior - it contains garbage values.
  2. Anywhere in the file after its declaration.
  3. %d

Practice

  1. Declare variables for storing a person's age, height (in cm), and first initial.
  2. Explain why this is dangerous: int x; printf("%d", x);