๐Ÿงท static Keyword in C Language

Lifetime, Scope, and Data Hiding

๐Ÿ”น What is static in C?

The static keyword in C is used to preserve the value of a variable and limit its scope. A static variable retains its value even after the function call ends.

Article Algo

๐Ÿ“Œ Uses of static in C

The static keyword is mainly used in:

  • Static local variables
  • Static global variables
  • Static functions

1๏ธโƒฃ Static Local Variable

Definition:

A static local variable is declared inside a function and retains its value between function calls.

Example:
#include <stdio.h>

void count() {
  static int x = 0;
  x++;
  printf("%d ", x);
}

int main() {
  count();
  count();
  count();
  return 0;
}
Output:
1 2 3

๐Ÿ‘‰ Normal local variables are destroyed after function execution, but static variables are not.

2๏ธโƒฃ Static Global Variable

Definition:

A static global variable is declared outside all functions but cannot be accessed from other files.

Example:
#include <stdio.h>

static int num = 100;

int main() {
  printf("%d", num);
  return 0;
}

โœ” Scope limited to the same source file only.

3๏ธโƒฃ Static Function

Definition:

A static function can be accessed only within the same file in which it is defined.

Example:
#include <stdio.h>

static void display() {
  printf("Static Function");
}

int main() {
  display();
  return 0;
}

โš–๏ธ Difference Between Static and Normal Variables

Feature Static Variable Normal Variable
Lifetime Entire program Until block ends
Value retention Yes No
Memory Allocated once Allocated multiple times
Default value 0 Garbage value

๐Ÿงช Example Showing Difference

#include <stdio.h>

void demo() {
  int a = 1;
  static int b = 1;
  a++;
  b++;
  printf("a=%d b=%d\n", a, b);
}

int main() {
  demo();
  demo();
  demo();
  return 0;
}
Output:
a=2 b=2
a=2 b=3
a=2 b=4

๐Ÿ“š FAQs on static in C

Q1. Why use static variables?

To preserve variable values between function calls.

Q2. What is the default value of a static variable?

The default value is 0.

Q3. Can static variables be initialized?

Yes, but only once.

Q4. What is the scope of a static variable?

Inside function โ†’ local scope
Outside function โ†’ file scope

Q5. Can static functions be called from another file?

No, static functions have file-level scope.

๐Ÿ”‘ Key Points to Remember

  • static increases variable lifetime
  • Value is preserved between calls
  • Improves data hiding
  • Default value is zero