Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
For example :
int a;
// global variable
void function1 ()
{
int b;
// local variable
b = 0;
}
void function2 ()
{
a = 1;
// a is a global variable
b = 2;
// b is a local variable but not visible as it is not
declared in this function
}
we can also call a variable as Local variable ,If we can also declare it in
the block or constructor.
void c()
{
int b=2;
{
int c=3;
cout<<c<<endl;
}
}
//
b is a local variable
If the global variable value is changed anywhere in the program (i.e. with
out declaring it ) ,it's value will be changed.
#include<iostream>
using namespace std;
int b=0;
// b is a global variable
void c()
{
cout<<"before change : "<<b<<endl;
b=2;
cout<<"after changed : "<<b<<endl;
{
int b=3;
// local variable
cout<<"in block : "<<b<<endl; // sets value to inner b
}
}
int main ()
{
c();
cout<<"in main : "<<b<<endl;
}
Suppose if u want two values for the same variable in the same function,
then a new concept namespace is to be used.
2.
#include <iostream>
using namespace std ;
int x=0;
void c()
{
cout << "x : " << x << '\n';
int x=4;
cout << "x : " << x << '\n';
}
int main ()
{
int x = 1;
int y = 2;
{
x = 3;
int y= 5 ;
cout << "x : " << x << '\n';
cout << "y : " << y << '\n';
}
c();
cout << "x : " << x << '\n';
cout << "y : " << y << '\n';
return 0;
3.
#include <iostream>
using namespace std ;
int x=0;
void c()
{
cout << "x : " << x << '\n';
x=4;
cout << "x : " << x << '\n';
}
int main ()
{
cout << "x : " << x << '\n';
{
x = 3;
int y;
y = 5;
cout << "x : " << x << '\n';
cout << "y : " << y << '\n';
}
c();
cout << "x : " << x << '\n';
cout << "y : " << y << '\n';
return 0;
}
4.
#include<iostream>
using namespace std;
int b=0;
class s
{
public:
s()
{
cout<<b<<endl;
int b=1;
cout<<b<<endl;
}
};
void c()
{
cout<<b<<endl;
b=2;
cout<<b<<endl;
int a=10;
{
cout<<a<< endl;
int b=3;
cout<<b<<endl;
}
}
int main ()
{
s d;
// calling constructor
b=9;
c();
cout<<b<<" " <<"main";
}
5.
#include<iostream>
using namespace std;
int b=0;
class s
{
public:
s()
{
cout<<b<<endl;
int b;
b=1;
cout<<b<<endl;
}
};
void d()
{
int a=15;
}
void e()
{
b=16;
}
void c(int a,int b)
{
cout<<a<<endl;
cout<<b<<endl;
{
int a=10;
b=12;
d();
e();
cout<<a<<endl;
cout<<b<<endl;
}
}
int main ()
{
s d;
c(6,7);
cout<<b<<endl;
}
The answers for this programs are available in the below link :
https://drive.google.com/folderview?id=0B5NxWL3Gw78dW1QMXlqWXdvdUk&usp=drive_web
FOR REFERENCES :
http://comsciguide.blogspot.in/2014/12/name-visibility-namedentities-suchas.html