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

Pass by reference confusion?


Consider this example:

void MyFunction(int &x){...}

void MyOtherFunction(int *x){...}

int main()
{
  int my_variable = 10;
  MyFunction(my_variable);
  MyOtherFunction(&my_variable);
}

Am I right in saying both the these methods are passing the variable by reference (i.e. not creating a copy), and the only difference is that MyOtherFunction is receiving a pointer?


Solution

  • You're right in saying that you don't copy my_variable, but a pointer is not a reference, they're two sets of distinct types.

    For example, a pointer can be null and you can call MyOtherFunction(nullptr).