- A scope in any programming is a part of the program where a defined variable can have access to whole the program or inside the main function or user defined function.
- Scope rule define the ability to access them in a program.
- Local Variable
- Global Variable
Local variable
- A local variable is a variable with local scope, meaning that it is not visible (hence not accessible) throughout the program.
- A local variable cannot access these to outside functions.
Example:
int sum(int a,int b)
{
int result;//local variable
result=a+b;
return result;
}
main()
{
int a,b,c;
printf("Enter two numbers to add:");
scanf("%d%d",&a,&b);
c=sum(a,b);
printf("SUM=%d",result);//cannot accees result in main
}
Global variable
- A global variable is a variable with global scope,meaning that it is visible(hence accessible) throughout the program.
- A global variable can access these to outside functions.
int sum(int,int);
int result;//Global variable
main()
{
int a,b,c;
printf("Enter two numbers to add:");
scanf("%d%d",&a,&b);
c=sum(a,b);
printf("SUM=%d",result);//cannot accees in main
}
int sum(int a,int b)
{
int result;//local variable
result=a+b;
return result;
}
Local functions
- Functions declared within the body of another function will have a local scope.
- It cannot acess outside world.
Global functions
- Functions declared outside the body of all other function will have a local scope.
- It can acess anywhere in the program.
int sum(int,int);
int result;//Global variable
main()
{
int a,b,c;
printf("Enter two numbers to add:");
scanf("%d%d",&a,&b);
c=sum(a,b);
printf("SUM=%d",result);//cannot accees in main
}
int sum(int a,int b)
{
int result;//local variable
result=a+b;
return result;
}