What is the difference between Local and Global Variables in Programming

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/01/difference-local-global-variables-programming/

A variable is a memory location inside memory which is referred using a name. The value inside a variable changes throughout the execution of the program. Based on where the variable is declared in the program, variables can be divided into two types. They are:

  1. Local Variables
  2. Global Variables

 

Local Variables

A variable is said to be a local variable if it is declared inside a function or inside a block. The scope of the local variable is within the function or block in which it was declared. A local variable remains in memory until the execution of the function or block in which it was declared in completes. Let’s see the following example:

In the above example, the variable x is a local variable with respect to the main function. Variable x is not accessible outside main function and x remains in the memory until the execution of the main function completes.

 

Global Variables

A variable is said to be a global variable if it is declared outside all the functions in the program. A global variable can be accessed throughout the program by any function. A global variable remains in the memory until the program terminates. In a multi-file program, a global can be accessed in other files wherever the variable is declared with the storage class extern.

Types of variables and their scope and lifetime can be summarized as shown below:

C program to demonstrate local and global variables:

In the above example, g is a global variable and x is a local variable with respect to main and y is a local variable within the block. The variable y cannot be accessed outside the block. That is why the printf statement outside the block accessing the value of the variable y has been commented out.

Take your time to comment on this article.

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2017/01/difference-local-global-variables-programming/

Add a Comment

Your email address will not be published. Required fields are marked *

Like the article? please consider sharing it. Thank you

Advertisment ad adsense adlogger