Skip to content

Scope of variables in C

Learn what scope is, and how it works in C

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:

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.

→ Download my free C Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about clang: