Scope is a region of the program where the variables can be accessed Scope contains a group of statements and variables Variables / Identifiers can be declared both inside and outside of block
Each identifier that appears in a C program accessed only in some possibly discontiguous portion of the program called its scope. The scope of variable depends upon it's place of declaration.
There are three places where a variable can be declared in a C program
Example to show use of Local Variables
#include<stdio.h>
#include<conio.h>
float getAreaOfRectangle(float length, float width){
/* local variable declaration */
float area;
/* area variable is only visible
inside getAreaOfSquare function */
area = length*width;
return area;
}
int main(){
/*length and width are local
variables of main function */
float length, width;
printf("Enter length and width of rectangle\n");
scanf("%f %f", &length, &width);
printf("Area of rectangle = %f", getAreaOfRectangle(length, width));
getch();
return 0;
}
Output
Enter length and width of rectangle
4.0 8.0
Area of rectangle = 32.000000
Example to show use of Global Variables
#include<stdio.h>
#include<conio.h>
/* Global variable declaration */
int area;
int main(){
int side;
printf("Enter side of square\n");
scanf("%d", &side);
/*Global Variables can be accessed from any function */
printf("Area Before = %d\n", area);
area = side*side;
printf("Area After = %d", area);
getch();
return 0;
}
Output
Enter side of square
5
Area Before = 0
Area After = 25
Formal Parameters in C are the arguments which is used inside body of function definition. Formal parameters are treated as local variables with-in scope of that function. It gets created when control enters function and gets destroyed when control exits from function.
Any change in the formal parameters of the function have no effect on the value of actual argument. If the name of a formal parameter is same as some global variable formal parameter gets priority over global variable.
Example to show use of Formal Parameters
#include<stdio.h>
#include<conio.h>
/* Global variable declaration */
int N = 100;
void printLocalValue(int N){
/* Inside function formal parameters and
* local variables get more priority over
* global variables
*/
printf("Value of N inside printLocalValue function : %d\n", N);
}
int main(){
/*
* main function can only access global variable N,
* not the formal parameter of printLocalValue function
*/
printf("Value of N inside main function : %d\n", N);
printLocalValue(50);
getch();
return 0;
}
Output
Value of N inside main function : 100
Value of N inside printLocalValue function : 50