difference between & and static

closed account (1vf9z8AR)
Is declaring a variable as static or passing it through a function using '&' mean the same thing?
In both cases the original value gets modified.

no. These things are not related at all!
static variables are never destroyed:

void foo()
{
static int x = 0;
cout << x++ << endl;
}

main()
{
foo(); //writes 0
foo(); //writes 1
foo(); //writes 2...
if you take the static keyword off, you get 0 every time.

& is address of / reference operator. It take an address of a variable:
int x;
int *ip = &x; //ip points to x now.

or as a reference parameter:
void foo(int &x) here, if x is changed inside foo it is changed where it was called from:
{
x = 4;
}

main
int y = 10;
foo(y);
cout << y << endl; //y is 4. foo changed it from &x reference parameter!

static variables are never destroyed

That's a little misleading - objects with static storage duration are destroyed at the end of the program.
closed account (1vf9z8AR)
thanks :)
Topic archived. No new replies allowed.