C Variables

In C programming, variables are used to store data of various types. Each variable is associated with a data type that determines the kind of data that can be stored in that variable. In this answer, we will discuss the different types of variables in C programming.

  1. Global variables:

Global variables are declared outside of any function and are accessible from anywhere in the program. They have a global scope and can be accessed by all the functions in the program. Global variables are initialized to zero by default.

Example:

#include <stdio.h>
int global_variable = 10;
void print_global_variable(){
    printf("Global variable = %d\n", global_variable);
}
int main(){
    print_global_variable();
    return 0;
}

output

Global variable = 10
  1. Local variables:

Local variables are declared inside a function and are accessible only within that function. They have a local scope and are destroyed when the function execution is completed. Local variables are not initialized by default and should be initialized before using.

Example:

#include <stdio.h>
void print_local_variable(){
    int local_variable = 20;
    printf("Local variable = %d\n", local_variable);
}
int main(){
    print_local_variable();
    return 0;
}

output

  1. Automatic variables:

Automatic variables are local variables that are declared without the static keyword. They are created and destroyed automatically when a function is called and returned, respectively. Automatic variables are not initialized by default and should be initialized before using.

Example:

#include <stdio.h>
void print_auto_variable(){
    int auto_variable;
    printf("Automatic variable = %d\n", auto_variable);
}
int main(){
    print_auto_variable();
    return 0;
}

output

Automatic variable = -1210276352
  1. Static variables:

Static variables are local variables that are declared with the static keyword. They have a local scope and are initialized to zero by default. Unlike automatic variables, static variables retain their value between function calls.

Example:

#include <stdio.h>
void print_static_variable(){
    static int static_variable;
    printf("Static variable = %d\n", static_variable);
    static_variable++;
}
int main(){
    for(int i=0; i<5; i++){
        print_static_variable();
    }
    return 0;
}

output

Static variable = 0
Static variable = 1
Static variable = 2
Static variable = 3
Static variable = 4