C Variable Scope

Variable in C differ in behaviour from those in most other language.In C not do all variable have a data-type,they also have a storage class.The following variable storage classes are most relevant to function:-

  1. Local Variable
  2. Global Variable
  3. Static Variable
  4. Register variable

In this tutorial, We discuss the scope and visibility of each of the above class variables.

The Scope of variable determines over what region of the program a variable is available for use while visibility refers to acessibility of a variable from the memory.It is very important understand the concept of storage classes and their utility in order to develop efficient multifunction program.

Automatic (Local) Variable

C Code Example

#include <stdio.h>


void main()
{
/* local variable declaration */
  int a = 2;
 
  printf ("value of a = %d",a);
 
 }

These are declared inside a function in which they are to be utilized. They are created when the function is called and destroying automatically when the function is exited, hence the name is automatic(Local). This assure that we may use declare and use the same variable name in different functions in the same program without causing any problem to the compiler.

main()
	{	
		data_type Variable_name;
		-----------
		-----------
	}

We may also use Keyword auto to declare Local variable:-

main()
	{	
		auto data_type Variable_name;
		-----------
		-----------
	}

External(Global) Variable

C Code Example

#include <stdio.h>


/* global variable declaration */
int a = 2;
 
void main () 
{
printf ("value of a = %d",a);
 }

These variables can be accessed by any function in the program. These are active in entire program that`s why it known as External or global variables. These are declared outside a function.

	
       data_type Variable_name;
	
	main()
		{	
			-----------
			-----------
		}
	function_name()
	{	
	 
			-----------
			-----------
	}

Static Variable

The value of static variable persists until the end of program.A variable can be declared static using the keyword static.A general form is:-

static data_type variable_name;

Register Variable

We can tell the compiler that a variable should be kept in one of the machine`s registers, instead of keeping the memory. Since register access is much faster as compared to memory access. keeping the frequently accessed variable(for example-loop control variable)in the register.A general form is:-

register data_type variable_name;

Since only few variables can be placed in the register, it is important to carefully select the variable for this purpose.However ,C will automatically convert register variable into non-register variable once the limit is reached.