C Advanced: Variable scope

When you define a variable in a C program, depending on where you declare it, it will have a different scope.

This means that it will be available in some places, but not in others.

The position determines 2 types of variables:

  • global variables
  • local variables

This is the difference: a variable declared inside a function is a local variable, like this:

int main(void) {
  int age = 37;
}

Local variables are only accessible from within the function, and when the function ends they stop their existence. They are cleared from the memory (with some exceptions).

A variable defined outside of a function is a global variable, like in this example:

int age = 37;

int main(void) {
  /* ... */
}

Global variables are accessible from any function of the program, and they are available for the whole execution of the program, until it ends.

I mentioned that local variables are not available any more after the function ends.

The reason is that local variables are declared on the stack, by default, unless you explicitly allocate them on the heap using pointers, but then you have to manage the memory yourself.

Lessons in this unit:

0: Introduction
1: Input and output
2: ▶︎ Variable scope
3: Static variables
4: Global variables
5: Type definitions
6: Enumerations
7: Structures
8: Command line parameters
9: Header files
10: The preprocessor
11: NULL values
12: Boolean values
13: Nesting functions
14: Conversion specifiers
15: Using quotes
16: String length
17: Returning strings
18: Array length
19: Looping through arrays
20: Checking character values
21: Printing percentage signs
22: Troubleshooting: Implicit function declarations

Join my AI Workshop!

The Web Development BOOTCAMP cohort starts in February 2026