Created: 2023-01-11 17:13
Status: #concept
Subject: Programming
Tags: C Variable Block Scope Scope Global Scope
Local Variable
These variables are only usable WITHIN { }
a specific Function scope or Compound Statement and will be deallocated once the function body terminates.
int sum_digits(int n)\
{
int sum = 0; // local variable
while (n > 0)
{
sum += n % 10;
n /= 10;
}
return sum;
}
The variable scoped to the function will get deallocated when the function exits, leading to the Pointer pointing to an invalid Memory Address.
- compilers will warn you, otherwise it will create a Segmentation Fault.
The static
Keyword
Using the
static
keyword to declare a variable will make a variable's storage duration Static instead of auto
.
- this means that storage is not deallocated when the Block Scope collapses.
#include <stdio.h>
int main(void)
{
count_down();
}
void count_down(void)
{
static int x = 10; // static declaration
if (x == 0) return; // base case
else
{
printf("%d ", x--); // decrement
count_down();
}
}
10 9 8 7 6 5 4 3 2 1
References
- C Programming, A Modern Approach, 2nd Edition, Chapter 10.1