In the previous blog post on C variables and types, we explored the basics of working with variables. Now, let’s dive deeper into the world of variables and understand the distinction between global and local variables.
A local variable is defined inside a function and is accessible only within that function. For example:
#include <stdio.h>
int main(void) {
char j = 0;
j += 10;
printf("%u", j); // Output: 10
}
In this case, variable j
is confined within the main
function and cannot be accessed outside of it.
On the other hand, a global variable is defined outside of any function, making it accessible to all functions within the program. Consider the following code snippet:
#include <stdio.h>
char i = 0;
int main(void) {
i += 10;
printf("%u", i); // Output: 10
}
Here, variable i
is accessible globally and can be accessed and modified by any function in the program. This enables us to share the same data across different functions.
It’s important to note that local variables are deallocated once the function execution ends, freeing up the memory they occupy. In contrast, global variables are only deallocated when the program terminates.
Understanding the difference between global and local variables allows developers to leverage the power of variable scoping to manage data effectively in their C programs.