# C Global Variables

> Learn how global variables work in C, defined outside any function so any function can read and update them, and how they differ from local variables.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2020-02-25 | Topics: [C](https://flaviocopes.com/tags/clang/) | Canonical: https://flaviocopes.com/c-global-variables/

In the [C variables and types](https://flaviocopes.com/c-variables-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: 

```c
#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:

```c
#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.
