Scope of static variables and global variables.

Hello coders! Welcome back!

Today we are going to look into the scope of variables- global variable Vs local variable.

Before that, first, let's understand what is the scope of a variable?  
  • The scope is nothing but the lifetime of a variable. The area under which the variable can be accessed/applicable/ alive. 
Let me explain with an example-

Here, we can see that I have declared 'varr' variable inside the main function, and tried to access it outside the function i.e, test function. And it shot an error saying varr is undeclared. The variable that is declared inside the main function, that variable cant be accessed outside the main function. Or in simple words, the variable that is declared in one block cant be accessed in another block are called local variables.

Let's look into another example- 

From the previous blog we have seen that we cant declare a variable twice, click here to view.

If you want to use the same variable twice in your code here is a way to do that-

Here it is important to note that the first print statement prints the nearest variable value that is available to it. And also we can use the same variable name by making them declare in different blocks, as another block cant access it.

Let's take another example to understand the scope of the global variable-


Here we can see that I have declared a variable outside the main function. And there is a function call test. The print statement inside the test function prints the global variable value.

The variable that is declared outside the main function, and accessible throughout the code/ program is called a global variable.

 Hope so you got a clear idea about the global and local variable. If any doubts drop a comment, always ready to clear your quarries.

Happy learning! 

Comments

Popular post