You are here: Home / Topics / Classification of Variables in C

Classification of Variables in C

Filed under: C Programming on 2022-07-05 21:37:02

The variables can be of the following basic types, based on the name and the type of the variable

  • Global Variable: A variable that gets declared outside a block or a function is known as a global variable. Any function in a program is capable of changing the value of a global variable. It means that the global variable will be available to all the functions in the code. Because the global variable in c is available to all the functions, we have to declare it at the beginning of a block.
    Example, 
    int value=30; // a global variable
    void function1(){
    int a=20; // a local variable
    }
  • Local Variable: A local variable is a type of variable that we declare inside a block or a function, unlike the global variable. Thus, we also have to declare a local variable in c at the beginning of a given block.
    Example, 
    void function1(){
    int x=10; // a local variable
    }
    A user also has to initialize this local variable in a code before we use it in the program.
  • Automatic Variable: Every variable that gets declared inside a block (in the C language) is by default automatic in nature. One can declare any given automatic variable explicitly using the keyword auto.
    Example, 
    void main(){
    int a=80; // a local variable (it is also automatic variable)
    auto int b=50; // an automatic variable
    }
  • Static Variable: The static variable in c is a variable that a user declares using the static keyword. This variable retains the given value between various function calls.
    Example,

 

void function1(){

int a=10; // A local variable

static int b=10; // A static variable

a=a+1;

b=b+1;

printf(“%d,%d”,a,b);

}

If we call this given function multiple times, then the local variable will print this very same value for every function call. For example, 11, 11, 11, and so on after this. The static variable, on the other hand, will print the value that is incremented in each and every function call. For example, 11, 12, 13, and so on.

  • External Variable: A user will be capable of sharing a variable in multiple numbers of source files in C if they use an external variable. If we want to declare an external variable, then we need to use the keyword extern.
    Syntax,

 

extern int a=10;// external variable (also a global variable)

About Author:
P
Parvesh Kanani     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.