Welcome to your guide on C Static Variables! In this lesson, we'll explore what static variables are, why they're useful, and how to use them in your C programs. Let's get started!
In C programming, a static variable is a variable that retains its value between function calls. Unlike regular variables, which are created and destroyed with each function call, static variables have a longer lifespan. They are stored in the data segment of the program, not on the stack.
Here's a simple example of a static variable in action:
#include <stdio.h>
void counter() {
static int count = 0; // Declare a static variable count
count++; // Increment the count
printf("Count: %d\n", count); // Print the count
}
int main() {
counter(); // Call the counter function
counter(); // Call it again
counter(); // Call it again
return 0;
}In this example, we declare a static variable count inside the counter function. Each time the function is called, the value of count is incremented and printed. Run this code, and you'll see that the count increases with each function call, demonstrating the persistence of static variables.
You can also declare static arrays, which are particularly useful for maintaining values across multiple function calls. Here's an example:
#include <stdio.h>
void max_num(int arr[], int size) {
static int max = arr[0]; // Declare a static variable max
for (int i = 0; i < size; i++) {
if (arr[i] > max) {
max = arr[i]; // Update max if a larger number is found
}
}
printf("Maximum number: %d\n", max); // Print the maximum number
}
int main() {
int numbers[] = {1, 5, 3, 7, 2};
max_num(numbers, sizeof(numbers) / sizeof(numbers[0]));
max_num(numbers, sizeof(numbers) / sizeof(numbers[0])); // Call the function again
return 0;
}In this example, we declare a static variable max inside the max_num function. Each time the function is called, it searches for the maximum number in the array and updates max accordingly. When you run this code, you'll see that the maximum number is printed correctly, demonstrating the use of static variables with arrays.
What is the main difference between regular variables and static variables in C programming?
That's all for this lesson on C Static Variables! In the next lesson, we'll dive deeper into more advanced C programming topics. Happy coding! 🚀