Click here to Skip to main content
15,877,103 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
void makeZero(Node* n){
        n = NULL;

int main(){
    Node* n = new Node (1);
    n -> next = new Node (2);
    n -> next -> next = new Node (3); 
    if(n == NULL){
        cout << "NULL";
        cout << "Not NULL";

In the above code when I try to make the n point to NULL it doesn't but when I change the function definition to
void makeZero(Node*& n)
it does the job. My doubt is why do I have to pass the reference to node as address only because the reference is itself an address so imo I am passing the address only even with the above code snippet.

If someone could resolve my doubt I would be really obliged. Thankyou.

What I have tried:

When I change the function definition to
void makeZero(Node*& n)
it does the job.
Updated 18-May-21 20:22pm

The reason is you passed the value of the pointer (an address) to the function on the stack. Changing that value does not change the original pointer because the value passed is just a copy. Passing a reference to the pointer allows you to change it in the function.
Share this answer
To add to what Rick said; by default all parameters passed to a function in C or C++ are passed by value: a copy of the value is made and that is passed to the function.
That makes sense if you think about it - what would happen if it wasn't, and the actual value was passed?
void foo (int x)
   x = x + 10;
That works fine for this:
int y = 666;
But what happens if you do this?
666 is a constant - you can't add ten to it and expect anything sensible to happen!

So parameters are passed by value and changes to the parameter inside the method do not affect the outside world:
void foo(int *x)
int y = 666;
int p = &y;
foo is passed a copy of the address that p points to, not the address of p - so changes to x inside the method do not affect p at all. To do that, you need to pass a reference to p, or a pointer to p.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900