In: Computer Science
execute coding examples that demonstrate the 4 scope rules
file,function,class,block
coding language c++
1. File scope example:
#include<iostream>
using namespace std;
int main()
{
{
int x = 10, y = 20;
{
// there is declaration of x and y in outer block
// this statement is work and print x=10 and y=20
cout<<"x = "<<x;
cout<<", y = "<<y<<endl;
{
// here, y is declared again and it can't
// access outer block y
int y = 40;
// increment the outer block variable, x to 11
x++;
// increment this block's variable y that is 41 now
y++;
// display x and y
cout<<"x = "<<x;
cout<<", y = "<<y<<endl;
}
// here, it will access only
// outer x and y
cout<<"x = "<<x;
cout<<", y = "<<y<<endl;
}
}
return 0;
}
OUTPUT:
------------------------------------------------------------------------------------------
Block scope:
#include<iostream>
using namespace std;
int main()
{
{
int x = 10;
}
{
// this will give error, becuase it cant access x
cout<<"x = "<<x;
}
return 0;
}
-----------------------------------------------------------------------------------------------
Function Prototype scope:
#include<iostream>
using namespace std;
int main()
{
// local variables
int x = 3, y = 5, z = 7;
cout<<"x = "<<x;
cout<<", y = "<<y;
cout<<", z = "<<z<<endl;
{
// change the value of variable x and y
int x = 10;
float y = 20;
cout<<"x = "<<x;
cout<<", y = "<<y;
cout<<", z = "<<z<<endl;
{
// change the variable z
int z = 100;
cout<<"x = "<<x;
cout<<", y = "<<y;
cout<<", z = "<<z<<endl;
}
}
return 0;
}
-------------------------------------------------------------------------------
Function scope:
YOu can use block space example in this function scope.
There willl be no change.
----------------------------------------
PLEASE UPVOTE