Static function in C
×


Static function in C

30

A static function in C is a function that retains its state between calls and is limited to the file where it's declared.

Unlike global functions, static functions can only be accessed within the same source file.

They are useful for encapsulating functionality that should not be exposed outside the file and for maintaining local state across multiple calls.

A static function in C is defined using the static keyword before the return type.

Syntax of Static in C:

static returnType functionName(parameters) {
    // function body
}

Visibility: A static function is only visible within the file where it is defined.

Lifetime: Its lifetime is throughout the program execution, but it's limited to the file it's declared in.

State Preservation: Static functions preserve their state between calls.

Programs:

Static Function to Count Function Calls

// Program for static function to count Function Calls
#include<stdio.h> 

void displayCount() {
    static int count = 0;
    count++;
    printf("Function has been called %d times.\n", count);
}

int main() {
    displayCount();
    displayCount();
    displayCount();
    return 0;
}

Output:

Function has been called 1 times.
Function has been called 2 times.
Function has been called 3 times.

Static Function for Fibonacci Series

// Program for static function for fibonacci series
#include<stdio.h> 

int fibonacci(int n) {
    static int a = 0, b = 1, result;
    
    if (n > 0) {
        result = a + b;
        a = b;
        b = result;
        printf("%d ", result);
        fibonacci(n-1);
    }
    return result;
}

int main() {
    printf("Fibonacci Series: ");
    printf("0 1 ");
    fibonacci(10);
    return 0;
}

Output:

Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 89 

Static Function to Calculate Factorial

// Program for static function to calculate Factorial
#include<stdio.h> 

int factorial(int n) {
    static int result = 1;
    if (n > 1) {
        result *= n;
        factorial(n-1);
    }
    return result;
}

int main() {
    int num = 5;
    printf("Factorial of %d is %d\n", num, factorial(num));
    return 0;
}

Output:

Factorial of 5 is 120

Program 1: Uses a static variable to count the number of times a function is called.

Program 2: Generates the Fibonacci series using static variables to maintain the state between function calls.

Program 3: Calculates the factorial of a number using a static variable to store and update the result.

In each program, the static function maintains its state across calls, demonstrating the key features of static functions in C.



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments