Scope of Variables in C
Learn about variable scoping in C and how it impacts the availability of variables within a program.
When you declare a variable in a C program, the scope of the variable is determined by where it is declared. This means that the variable will be accessible in certain parts of the program, but not in others.
There are two types of variables based on their scope: global variables and local variables.
A local variable is declared inside a function and is only accessible within that function. Once the function ends, the local variable ceases to exist and is cleared from memory (with some exceptions). Here’s an example:
1 | int main(void) { |
On the other hand, a global variable is declared outside of any function and is accessible from any function within the program. It is available for the entire execution of the program until it ends. Here’s an example:
1 | int age = 37; |
It’s worth noting that local variables are not available after the function ends because they are declared on the stack by default. However, you can explicitly allocate them on the heap using pointers if you need to manage the memory yourself.
Tags: C programming, variable scoping, global variables, local variables