Created: 2023-01-11 17:13
Status: #concept
Subject: Programming
Tags: C Variable Block Scope Scope Global Scope

Local Variable

A kind of variable with Automatic Storage Duration & Block Scope.

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 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