Search code examples
c++pass-by-referencepass-by-pointer

Pass by reference using pointer and dereference pointer


Which one is better: Pass by Reference using void increment(int& x) or Pass by Pointer using void increment(int* x)?

  1. void increment(int& x)
    {
        x=x+1;
    }
    int main()
    {  
        int n= 2;
        increment(n);
        cout << "Value of n is " << n << '\n';
        return 0;
    }
    

    or

  2. void increment(int* x)
    {
        *x=*x+1;
    }
    int main()
    {  
        int n= 2;
        increment(&n);
        cout << "Value of n is " << n << '\n';
        return 0;
    }
    

Solution

  • None is better. The advantage of using pointer is that it makes explicit in the calling code that the argument is passed by pointer, since the argument is preceded with &. The advantage of using reference is that it is more natural in the calling function code, without all * dereferences. Internally the are normally implemented in the same way, so there should be no speed advantages.