Thursday, November 21, 2013

Does int*& scare you ?

When you see a function declaration like this "void f(int*&); ", does it
scare you a little?  Pass-by-reference seems to be an unique feature in C++ program language, not in c, not in java, not in python. What it means is like
someone walks into a function itself, then whatever you do to that guy inside the function has effects to that guy because it's THAT guy in the function, not somebody else.

Now let's back to int*& in "void f(int*&);",  what it means is a variable( let's say its name is ip) , whose value is a memory address, walks into f() itself. 

Normally we can change the content in that address via *ip.
    For example, *ip  = 4;

But this time, we can also change its value by assigning another address to it.
    For example,  ip = new node();

After you've done that, ip refers to a totally different memory location, not the previous memory address anymore.

In short, if you pass a "address type", which is T*,  variable into a function by reference, then you can assign a new address to that variable inside the function. After the function is gone, that variable now refers to a new address. It's just simple like that. 

Example:

struct node
{
    int a;
    node* next;
};

typedef node* ADDR;

// void f(ADDR& change, ADDR noChange)    // not that scaring.
void f(node*& change, node* noChange)       // a little scaring
{
    // Create an address tmp.
    ADDR tmp = new node();
    tmp->a = 100;
    tmp->next = NULL;

    // Assign the new address to both change and neverChange
    // Now variable "change" that comes into f() itself is assigned with a new address.
    change = tmp;
    // Local variable "noChange", NOT variable "noChange" coming into f(),  is assigned with a new address.
    noChange = tmp;

    // Normally we modify the contents of the address.
    // but this time I don't do it.
    // *change = *tmp;
    // *noChange = *tmp;
}


Test code: 

        ADDR change = new node();   
        ADDR noChange = new node();
   
        change->a = 10;
        change->next = NULL;

        noChange->a = 10;
        noChange->next = NULL;

        cout << "Addresses are " << change  << "   "  << noChange << endl;
        cout << "Value are " << change->a  << "   "  << noChange->a << endl;
        f(change, noChange);
        cout << "Addresses are " << change  << "   "  << noChange << endl;
        cout << "Value are " << change->a  << "   "  << noChange->a << endl;

Result: 

Addresses are 0x79c320   0x79c340
Value are 10   10
Addresses are 0x79c360   0x79c340
Value are 100   10


No comments:

Post a Comment