Scope of variable in C | Local variable in C | Global variable in c

Preview
You must first complete What is a variable in C Language before viewing this Lesson

Scope of variable in C

Scope is the lifetime of variables. Variables have two types depending upon scope.

  • Local variable
  • Global variable



 a.  Local variable

Variable declared inside a function body is called local variable. It can exist only within the function in which it is declared.

 b. Global variable

Variable declared before all function definitions is known as global variable. The value of global variable exists throughout the program. Changes made to them have effect on entire .

Program for local and global variables.
#include<stdio.h>
int a=10; /*global variable*/
void show()
{
printf(“\nGlobal variable in show() %d”,a);
a++;
}
int main()
{

int k=50; /*Local variable*/

printf(“Local variable in main=%d”,k);
printf(“Global variable in main()=%d”,a);
++a;
show();
printf(“Global variable in main()=%d”,a);
return(0);
}

Output
Local variable in main=50
Global variable in main() =10
Global variable in function a=11
Global variable in main() a=12

Best Books of C





Lesson tags: global variables in c, local variables in c, program of global variable, program of local variable, variable scope in c
Back to: C Programming Language