Site icon NexGismo

Static Variables in Functions: Unleashing Their Power

STATIC VARIABLES
void counterFunction() {  
    static int counter = 0; // Static variable  
    counter++;  
    printf("Counter: %d\n", counter);  
}  
  
int main() {  
    counterFunction(); // Output: Counter: 1  
    counterFunction(); // Output: Counter: 2  
    counterFunction(); // Output: Counter: 3  
    return 0;  
}  
#include <stdio.h>  
  
static int globalCounter = 0; // Global static variable  
  
void incrementCounter() {  
    globalCounter++;  
}  
  
void printCounter() {  
    printf("Global Counter: %d\n", globalCounter);  
}  
  
int main() {  
    incrementCounter();  
    incrementCounter();  
    printCounter(); // Output: Global Counter: 2  
    return 0;  
}  
#include <stdio.h>  
  
void localStaticFunction() {  
    static int localCounter = 0; // Local static variable  
    localCounter++;  
    printf("Local Counter: %d\n", localCounter);  
}  
  
int main() {  
    localStaticFunction(); // Output: Local Counter: 1  
    localStaticFunction(); // Output: Local Counter: 2  
    localStaticFunction(); // Output: Local Counter: 3  
    return 0;  
}  
#include <stdio.h>  
  
int fibonacci(int n) {  
    static int memo[1000] = {0}; // Memoization array  
  
    if (n <= 1) return n;  
  
    if (memo[n] != 0) return memo[n];  
  
    memo[n] = fibonacci(n - 1) + fibonacci(n - 2);  
    return memo[n];  
}  
  
int main() {  
    printf("Fibonacci(10): %d\n", fibonacci(10)); // Output: Fibonacci(10): 55  
    return 0;  
}  
#include <stdio.h>  
  
void gameScore() {  
    static int score = 0; // Static variable to track score  
    score += 10;  
    printf("Current Score: %d\n", score);  
}  
  
int main() {  
    gameScore(); // Output: Current Score: 10  
    gameScore(); // Output: Current Score: 20  
    gameScore(); // Output: Current Score: 30  
    return 0;  
}  
Exit mobile version