Created: 2023-01-11 17:26
Status: #concept
Subject: Programming
Tags: C Variable Local Variable
Static
Static objects allow us to retain information during the execution of a program.
C
static
objects retains their value when INSIDE its corresponding Compound Statement Block Scope or Function scope for the entire duration of the program.
- they have to be Constant values because they are evaluated during compilation and not runtime.
In that context, they have Static Storage Duration and Block Scope.
static
Variables in Functions
Because
static
variables exist during the entire execution of a program, we can return static
Variables' Memory Addresses and Dereference them outside the function.
auto
Automatic Storage Duration variables on the other hand get deallocated after its Local Scope ends and cannot be returned as a Pointer.
#include <stdio.h>
int *count(int x)
{
static int count = 0;
count += x;
return &count; // add '&' to give back the memory address for static variables
}
int main(void)
{
int x = 5;
/* note how we have to add * before the function call to dereference */
printf("%d\n", count(x)); // prints a random large integer address
printf("%d\n", *count(x)); // dereferences static variable 'count' & prints 5
printf("%d", *count(10)); // prints 20
}
References
- C Programming, A Modern Approach, 2nd Edition, Chapter 10.2
- C Programming, A Modern Approach, 2nd Edition, Chapter 11.5