c
  1. c-static

C Static Keyword

Syntax

static data_type variable;
static function_return_type function_name(data_type parameter);
static int counter = 0;

Example

#include <stdio.h>

int main() {
  static int count = 0;
  
  printf("The value of count is %d\n", count);
  
  count++;
  
  printf("The value of count is now %d\n", count);
  
  return 0;
}

Output

The output of the above code will be:

The value of count is 0
The value of count is now 1

Explanation

In C language, the static keyword has a number of uses:

  1. For variables, static is used to preserve the value of a variable between function calls.
  2. For functions, static is used to reduce name clashes between functions with the same name in different source files.
  3. For structures and unions, static means that the definition is not visible outside of the current source file.

Use

The primary use for the static keyword in C is to control the scope and lifetime of variables and functions, allowing for more efficient and safer programming. It allows for the reuse of function and variable names without conflicts and allows for variable values to be preserved across function calls.

Important Points

  • A static variable is initialized only once, at the time of declaration, and its value persists throughout the execution of the program.
  • A static function is only visible to other functions in the same source file.
  • static variables are not accessible from outside the block or function in which they are declared.
  • static variables are stored in the data segment of the program's memory, rather than on the stack.

Summary

The static keyword in C has a number of uses in controlling the scope and lifetime of variables and functions. It allows for the reuse of names without conflicts and ensures the preservation of variable values between function calls. Understanding the uses and limitations of static is an important part of writing efficient and safe C programs.

Published on: