Skip to content

Static variables in C

How to work with static variables in C

Inside a function, you can initialize a static variable using the static keyword.

I said "inside a function", because global variables are static by default, so there's no need to add the keyword.

What's a static variable? A static variable is initialized to 0 if no initial value is specified, and it retains the value across function calls.

Consider this function:

int incrementAge() {
  int age = 0;
  return age;

If we call incrementAge() once, we'll get 1 as the return value. If we call it more than once, we'll always get 1 back, because age is a local variable and it's re-initialized to 0 on every single function call.

If we change the function to:

int incrementAge() {
  static int age = 0;
  return age;

Now every time we call this function, we'll get an incremented value:

printf("%d\n", incrementAge());
printf("%d\n", incrementAge());
printf("%d\n", incrementAge());

will give us


We can also omit initializing age to 0 in static int age = 0;, and just write static int age; because static variables are automatically set to 0 when created.

We can also have static arrays. In this case, each single item in the array is initialized to 0:

int incrementAge() {
  static int ages[3];
  return ages[0];
→ Download my free C Handbook!



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: