C - Local Variables and Global Variables

In C programming, variables can be categorized into two main types based on their scope and lifetime: local variables and global variables. Here's an explanation of each type:

Local Variable:

A local variable is a variable declared within a block of code, typically within a function. Local variables are only accessible within the block or function where they are declared. They have limited scope and lifetime, which means they exist and can be used only within the specific block or function in which they are defined. Once the execution of the block or function is completed, local variables go out of scope, and their memory is released.


#include <stdio.h>

int main() {
    int x; // Local variable
    x = 5; // Assign a value to x
    printf("Local variable x: %d\n", x);
    return 0;
}
    
Global Variable:

A global variable is a variable declared outside of all functions, typically at the top of a source file. Global variables have a broader scope than local variables. They can be accessed and used from anywhere in the source file where they are declared. Global variables have a lifetime that extends throughout the entire program's execution, and they retain their values until the program terminates.


#include <stdio.h>

int globalVar = 10; // Global variable

int main() {
    printf("Global variable: %d\n", globalVar);
    return 0;
}
    

It's important to use local variables when you need variables with a limited scope that are specific to a particular block or function. Global variables should be used sparingly because they can make the code less modular and harder to understand due to their wide accessibility. In general, it's considered good practice to minimize the use of global variables and prefer local variables when appropriate to encapsulate data within specific functions or blocks.