×

C Tutorial

C Basics

C Data Types

C Input/Output

C Operators

C Conditional Statements

C Control Statements

C Strings

C Functions

C Arrays

C Structure and Unions

C Pointers

C Preprocessor Directives

C Command-line Arguments

C File Handlings

C Graphics

C Advance Topics

C Tips and Tricks

C Important Topics

C Practice

Difference between local and global variables (Scopes)

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 [Last updated : March 14, 2023]

Scope of variables in C

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.

C Language Tutorial »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.