Skip to content

C Global Variables

New Course Coming Soon:

Get Really Good at Git

An introduction to C Global Variables

In the C variables and types post I introduced how to work with variables.

In this post I want to mention the difference between global and local variables.

A local variable is defined inside a function, and it’s only available inside that function.

Like this:

#include <stdio.h>

int main(void) {
  char j = 0;
  j += 10;
  printf("%u", j); //10
}

j is not available anywhere outside the main function.

A global variable is defined outside of any function, like this:

#include <stdio.h>

char i = 0;

int main(void) {
  i += 10;
  printf("%u", i); //10
}

A global variable can be accessed by any function in the program. Access is not limited to reading the value: the variable can be updated by any function.

Due to this, global variables are one way we have of sharing the same data between functions.

The main difference with local variables is that the memory allocated for variables is freed once the function ends.

Global variables are only freed when the program ends.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my C Handbook

Here is how can I help you: