Address
-
A variable may have
different addresses at different times during execution
-
A variable may have
different addresses at different places in a program
-
If two variable names
can be used to access the same memory location, they are called
aliases
-
Aliases are created
via pointers, reference variables, C and C++ unions
-
Aliases are harmful
to readability (program readers must remember all of them)
-
Memory Address is called l-value.
( l means left)
-
Variables appear on the left of assignment statement.
-
Same Name can be associated with different memory location.
-
e.g. a reference to sum
in subprogram 1 is unrelated to reference to sum
in subprogram 2.
#include
<iostream>
using
namespace std;
int
temp = 5;
int passfun(int x);
int main(){
int
temp = 10;
temp
= passfun(temp);
cout << "temp in
main = " << temp <<
endl;
return 0;
}
int passfun(int x){
cout << "temp in
subprogram = " << temp <<
endl;
return x +
temp;
}
-
e.g. a recursively called subprogram has multiple versions of each
locally declared variable, one for each activation.
- Python programs
- Static Scoping or Dynamic Scoping
-
Aliases:
When more than one name is associated with a single memory location, the
names are aliases.
-
To create alias:
-
FORTRAN use EQUIVALENCE
-
Pascal, Ada use variant record structure
-
C, C++ use union type
-
Two pointer variables reference to the same memory location.
-
Readability: Aliasing is a hindrance to readability
because it allows a variable
to have its value changed by an assignment to a different variable
e.g. If A & B are aliases, any change to A also change to
B..
-
Reusing storage: It is not so important now since
computer memories are far larger now.
-
Interface between subprograms:
e.g. In C++, use reference parameters to pass information.
#include <iostream>
using
namespace std;
void getData(int &A,
int &B);
int main()
{
int num1,
num2;
getData(num1,
num2);
cout<<"The
sum of "<<num1<<" and "<<num2<<" is "<<num1+num2<<endl;
return 0;
}
void getData(int &A,
int &B)
{
cout<<"Please
enter two numbers. \n";
cin>>A>>B;
}