-->

Scope Rules

Scope Rules in C Language
Scope Rules
The scope of an identifier is the portion of the program in which the identifier can be referenced.
For example, when we define a local variable in a block, it can be referenced only by following its definition in that block or in blocks nested within that block.

#include<stdio.h>
float length, breadth; //External global variables
int main()
{
printf(“Enter length, breadth:”);
scanf(“%f%f”,&length, &breadth);
area();
perimeter();
printf(“\nEnter length,breadth:”);
scanf(“%f%f”,&length, &breadth);
area();
perimeter();
}
void area()
{
static int num=0; /Static local variables
float a; //automatic local variables
num++;
a=(length*breadth);
printf(“\nArea of rectangle %d: %2f”, num,a);
}
void perimeter()
{
int no=0; //automatic local variables
float p;  //automatic local variables
no++;
p=2*(length + breadth);
printf(“Perimeter of rectangle %d: %2f”, no, p);
}

External Global Variables
Scope: Visible across multiple functions. 
Lifetime: Exists till the end of the program.

Static Local Variables
Visible within the function, created only once when the function is called for the first time and exists between function calls.

Automatic Local Variables
Scope: Visible within the function.
Lifetime: Re-created for every function call and destroyed automatically when function is exited.

OUTPUT:
Enter length, breadth: 6 4
Area of rectangle 1: 25.00
Perimeter of rectangle: 20.00
Enter length, breadth: 8 5
Area of rectangle 2: 40.00
Perimeter of rectangle: 26.00

File1.c
#include<stdio.h>
float length, breadth; 
static float base, height; 
int main() 
{
float peri; 
printf("Enter length, breadth : "); 
scanf("%f%f",&length,&breadth); 
rectangleArea() ; 
peri = rectangleperimeter(); 
printf("perimeter of Rectangle : %f", peri); 
printf("\nEnter base , height: ");
scanf("%f %f",&base,&height); 
triangleArea() ; 
void rectangleArea() 
float a; 
a = length * breadth; 
printf("\nArea of Rectangle : %2f",  a);
}
void triangleArea() 
float a; 
a = 0.5 * base * height ; 
printf("\nArea of Triangle : %.2f", a);
}

File2.c 
extern float length, breadth ; 
/* extern base , height ; --error */
float rectangleperimeter() 
{
float p; 
p = 2 *(length + breadth); 
return ( p );
}



Related Posts

Subscribe Our Newsletter