0

I wrote following code using int* input and int& input and both works same. What is difference and what is right approach to pass reference?

#include<iostream>

void increment(int* input);

int main()
{
    int a = 34;
    std::cout<<"Before the function call a = "<<a<<"\n";
    increment(&a);
    std::cout<<"After the function call a = "<<a<<"\n";
    return 0;
}

void increment(int * input)
{
    (*input)++;
    std::cout<<"In the function call a = "<<*input<<"\n";    
}

Following code also works fine.

#include<iostream>

void increment(int &input); 

int main()
{
    int a = 34;
    std::cout<<"Before the function call a = "<<a<<"\n";
    increment(a);
    std::cout<<"After the function call a = "<<a<<"\n";
    return 0;
}
void increment(int &input)//Note the addition of '&'
{
    input++; //**Note the LACK OF THE addition of '&'**
    std::cout<<"In the function call a = "<<input<<"\n";
}

Any idea?

joy
  • 3,669
  • 7
  • 38
  • 73
  • 1
    Difference is only one thing: preferred coding standard. Some think pointer version is better since it is easy to spot "out" argument, others think it is better to have reference to indicate that `nullptr` is not acceptable. Basically answer is opinion based. From generated code perspective - no difference. – Marek R Aug 11 '22 at 16:52
  • If you want to pass reference use &, because other thing is a value. – Revolver_Ocelot Aug 11 '22 at 16:54
  • @MarekR: That's true with one exception: when the compiler converts another syntax into a function call (implicit conversion, operator overloading, etc) then the function needs to use a reference to the operand type. That way the operand can itself have a pointer type, and the function can be overloaded to distinguish. – Ben Voigt Aug 11 '22 at 16:56

0 Answers0