Global variable and local variable

Global variable and local variable are the terms related to visibility or accessibility of variables. Variables declared in different scope of programming languages  like C,C++,JAVA  have different life time.

How to declare global variable and local variable ?

The variable declared outside the main functions are known as global variable.In a single program there could be number of global variable as per the requirements in program.Global variable are known to all functions present in the programs.The life time of global variables till the life time of program.Global variables can be called from different block of functions.The value of global variable remain same for all functions.By default the value of global variable is 0.


The variable declared inside the block of functions are known as local variable.The scope of these variables are only inside the block of particular function. They are unknown outside of respective functions.The lifetime of local variables are till the end of scope of respective functions. As the scope of functions ends the lifetime or existence of local variables also ends.


Note:If the variable having same name is declared as global as well local in such situation the function will use local variable and ignore the global variable.

Variable having same name must be avoided.Its beneficial to use different variable name as  global and local variable.Using of less number of global variable makes program better efficient.

How to access global variable and local variable ?

Local variable can be accessed directly by using the variable name inside the function.Global variables can be accessed by using the function in C.  Accessing global variable using scope resolution operator (::) in C will lead to error. Go through the code snippets given below it will be more clear how to access these variables:

Program compiled in Dev C++ compiler.

In the above program variable k is made as local as well as global.Here both the variable has same name so the value of global variable is ignored.


Program compiled in Dev C++ compiler:


In the above program inside the function f1() the local variables are not present hence the global variable are used.

In the above program scope resolution operator is used hence it will show you error.We cannot access global variable using scope resolution operator in C.
Click here for more programs.







Leave a Reply