Local static
Local Static Local static is a type of variable that is allocated memory within a function and is accessible only within that function. Unlike global var...
Local Static Local static is a type of variable that is allocated memory within a function and is accessible only within that function. Unlike global var...
Local static is a type of variable that is allocated memory within a function and is accessible only within that function. Unlike global variables, which are allocated memory in the program's memory space, local static variables are allocated on the function stack.
Example:
c
void print_message(void) {
static char message[10]; // Local static variable
message[0] = 'H';
message[1] = 'i';
message[2] = 'l';
message[3] = 'o';
message[4] = '\0';
printf(message);
}
Explanation:
The static keyword is used before the variable declaration to specify its scope as local.
The variable message is declared on the function stack, meaning it is allocated memory on the call stack.
This means that the variable's lifetime is tied to the function and is not affected by the program's scope.
The variable is initialized with the character 'H', and the rest of the string is constructed by the function.
Since the variable is allocated on the stack, it is destroyed when the function exits, and its memory is released.
Key points about local static:
They are accessible only within the function where they are declared.
They are allocated on the function stack, not in the program's memory space.
They are destroyed when the function exits.
They can be used to store data that should be preserved across function calls