Local and Global Variables

Variable name not defined is a common error faced by programmers. It is very important to know about local and global variable declarations. In this blog, we learn the difference between local and global variables.

First thing we need to know here is the definition of scope of a variable. The scope of a variable is defined as the region in a program where a defined variable can have its existence and beyond the scope the variable cannot be accessed.

A global variable, as its name suggests , can be accessed anywhere. A local variable is a variable that can be accessed within its scope where it is defined .That is within the block of function where it is defined.

Local variables

Let us see an example of local variables.screenshot-2.png

In this function called max , we use 2 variables a and b. a and b are both defined inside the function. So the scope of variables a and b is within the function max. Outside the function max, a and b do not exist. So a and b are local variables. Let us try accessing a outside the function max.

 

screenshot-6.png

As we can see, when we tried to print a outside the function, there is an error saying a is not defined. This is because a is a local variable that can be operated on only within the function max.

Global variables

A global variable as defined earlier  can be accessed from any place in the program. Let us look at the following example. I am defining a variable c = 10. If a is greater than b , we return a+10 or else we return b+10.  So here c is accessed from within the function max though it is not defined inside it.

screenshot-8.png

Here c is a global variable. But we do not have to use “global” keyword here as we are only accessing c. Now if you want to modify c you need to specify it as global or else it will give an error.screenshot-9.png

screenshot-103.png

Hope the concept of local and global variables is clear.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: