Home » C programming language

What is the Scope in C language? Write difference between local and global variables/Scope



In this tutorial, we are going to learn about the Scopes in C programming language. We will learn: What is Scope and what are the difference between Local and Global Scopes/Variables?
Submitted by IncludeHelp, on May 12, 2018

The scope is a particular region in the program, where variables, constants have their existence and can be accessed. In other words, we can say that “the area where a variables, constants are accessible known as Scope of a variable.

Scope defines the following things:

  • Accessibility of a variable, constant
  • Lifetime of a variable, constant
  • Memory segment where the memory bytes should be reserved for the variables, constants
  • Deallocation time of the reserved memory bytes

Example code:

#include <stdio.h>

/*global scope*/
int a = 10;

void fun(void)
{
	/*local scope to this function only*/
	int c=30;
	printf("a =%d, c=%d\n",a,c);
}

int main()
{
	/*local scope*/	
	int b=20;
	printf("a=%d, b=%d\n",a,b);
	fun();
	
	return 0;
}

Output

    a=10, b=20
    a =10, c=30

In the above code,

  • a is global variable and it is accessible in any scope of the program, we have used it in main() as well as fun() function.
  • b is a local variable of main() and it is accessible only in main() function.
  • c is a local variable of fun() and it is accessible only in fun() function.

Difference between global and local scope

Local scope Global scope
The variables which are declared in local scope (scope of any function) are known as local variables to that function. The variables which are declared in Global scope (outside of the main) are known as Global variables to the program.
These variables can be accessible within the same block only in which they are declared. These variables can be accessible within the complete program (in all functions).
Memory is released when program’s execution comes out from the scope. Memory is released when program’s execution finishes.
Variables declared inside the local scope are stored in stack segment, unless specified. Variables declared inside the Global scope are stored in data segment.





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.