Static variables in C

How to use static variables in C

Inside the function, you can initialize aStatic variableusestaticKey words.

I say "inside a function" because global variables are static by default, so there is no need to add keywords.

What is a static variable? If the initial value is not specified, the static variable is initialized to 0 and the value is retained during the function call.

Consider the following functions:

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

If we callincrementAge()Once we will get1As the return value. If we call it multiple times, we will always get 1 becauseageIs a local variable, it is reinitialized to0On every single function call.

If you change the function to:

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

Now, every time this function is called, we will get an increasing value:

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

Will give us

1
2
3

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];
  ages[0]++;
  return ages[0];
}

Download my free C Handbook


More clang tutorials: