Ok, let's dissect this small program
int& add()
{
static int a;
a++;
cout<<"\na="<<a;
return a;
}
static int a declares a variable. Static in this context means that there is only on place to store a and that place is used whenever add is called. So a is like a global variable that can only be accessed inside add.
The return value is a reference. Most compiler use pointer internally to represent reference. What you can see here is that a reference to the static variable a is returned. Anyone can change a once he obtained the reference.
The a++ and the cout is straightforward - no further comments here.
int main{
int x,y,m; // declare three ints: x,y,m, all unassigned
int &z = add(); // a is incremented to 1, z is a reference to a
x=add(); // add() returns a reference to a, x copies the value of a
y=add(); // same as above
z++; // increments a, since z is a reference to a
m=add(); // same as x and y, copies the value of a
cout<<"\nx="<<x<<"\ny="<<y<<"\nz="<<z<<"\nm="<<m;
return 0;
}
int &z = add(); calls add - which means that a is incremented. z is now an alias for the static variable a since it uses the reference. x=add(); increment a again but now copy the value of a since x is not of type int& but of type int. y - same.
z++: since z is an alias for a - increment a without printing it via cout.
m=add(): increment a, copy a int m like x and y.
The output is straightforward once you understand why x,y,m are copies and z is an alias.
Any questions still open?
regards
Tobias