1. When a variable is preceded with the keyword static, it becomes a part of the Data Segment in the Process Context. Since the data segment is itself divided into the initialized data section and uninitialized data section, static variables can be placed in either based on whether they are explicitly initialized.
2. When a variable is declared as static since it becomes a part of the data segment, hence, it retains its value during various function calls.
3. If a variable is defined as static within a function, it means although the variable belongs to a local function but It won't be a part of the Stack segment.
In our previous discussion, we delved into the behavior of static variables in C, with a focus on Example 1. Now, let's continue our exploration by diving into Example 2 to further understand the nuances of static elements.
static int moduleVariable = 5; // Static variable accessible by functions in this module
void functionA(int a)
{
moduleVariable = moduleVariable + a;
printf("Function A: %d\n", moduleVariable);
}
void functionB(int b)
{
moduleVariable = moduleVariable - b;
printf("Function B: %d\n", moduleVariable);
}
OUTPUT:
Function A: 10
Function B: 8
Note that in this example static variable is defined in the Global section of the program module.c. So, this variable can only be accessed by the functions that are a part of this file i.e., functions functionA() and functionB() can access it but Not main(). If the main() function tries to access the static variable. it can be done indirectly by either functionA() or functionB().
The conclusion that is dawn from the above discussion about Static keyword:
1. Extended Lifetime: Static variables have a lifetime that extends throughout the entire program execution, unlike local variables in functions, which have a shorter lifetime.
2. Default Initialization: Static variables are initialized to 0 by default if no explicit initialization is provided.
3. Data Segment Placement: In both examples, the static variables (staticVar and moduleVariable) are indeed part of the data segment. However, their scope and accessibility differ:
staticVar: Has local scope, meaning it's only accessible within exampleFunction.
moduleVariable: Has file-static scope, meaning it's accessible only within functions defined in module.c and hence, promotes data protection.
Let's continue this discussion and learn from each other's perspectives! Next, we will explore the static function in C.