Scope Resolution and Reference Variable
Scope Resolution and Reference Variable
variable.
• Once a reference is initialized with a variable, either the variable name or the
reference name may be used to refer to the variable.
• Syntax :
• Datatype & reference _name = variable _name;
• Int x=100;
1002 Location address
• Int y=x;
• x++;
1004 Location address
• cout<<x;
• cout<<y;
•}
x/y Location name
• Int &y=x;
• x= x+10;
1002 Location address
• cout<<x; //o/p 110
int main () {
// declare simple variables
int i;
double d;
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
Table 1
Value of i : 5
Value of i re ference : 5
Value of d : 11.7
Value of d re ference : 11.7
#include<iostream>
using namespace std;
int main()
{
int x = 10;
// ref is a reference to x.
int& ref = x;
return 0;
}
Output:
x = 20
ref = 30
C++ Scope resolution operator
•#
• # include<iostream.h> • # include<iostream.h>
• Int i=10; • Int i=10;
• Void main() • Void main()
•{ •{
• Int j=20; • Int i=20;
• Cout <<i<<endl; • Cout <<i<<endl;
• cout<<j; •}
•}
• o/p
• o/p • 20
• 10
• 20
• main()
• {
• Int i=5;
• {
Inner block Outer block
• i=10;
• cout<<i; // 10
• }
• }
• A variable I.e declared inside a function is called as “local
variable”.
• Cpp allows the user the flexibility of accessing both the variable
.it achieve this with the help of new operator called as “scope
resolution operator “ .
#include<iostream.h> M
Int m=10;
10
main()
{
1002
Int m=20;
Int k=m; M
{
20
cout<<“we are in inner block”;
cout<<“k=“<<k; // 20
cout<<“m=“<<m; // 20
1004
K
cout<<“:: m=“<<:: m; //
}
20
cout<<“we are in outer block”;
cout<<“m=“<<m;
1006
cout<<“::m”<<::m;