2

What is the difference between the following parameter passing mechanisms in C++?

void foo(int &x) 
void foo(int *x)
void foo(int **x)
void foo(int *&x)

I'd like to know in which case the parameter is being passed by value or passed by reference.

user246392
  • 2,661
  • 11
  • 54
  • 96

2 Answers2

8
void foo(int &x)

passes a reference to an integer. This is an input/output parameter and can be used like a regular integer in the function. Value gets passed back to the caller.


void food(int *x)

passes a pointer to an integer. This is an input/output parameter but it's used like a pointer and has to be dereferenced (e.g. *x = 100;). You also need to check that it's not null.


void foo(int **x)

passes a pointer to a pointer to an integer. This is an input/output parameter of type integer pointer. Use this if you want to change the value of an integer point (e.g. *x = &m_myInt;).


void foo(int *&x)

passes a reference to a pointer to an integer. Like above but no need to dereference the pointer variable (e.g. x = &m_myInt;).


Hope that makes sense. I would recommend using typedefs to simplify the use of pointers and reference symbols.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
Joe Wood
  • 1,321
  • 2
  • 13
  • 25
  • The last one is a pointer to a reference, it would still need to be dereferenciated. A reference to a pointer would be declared like `void foo(int &*x)` – Vargas Sep 20 '10 at 00:15
  • 2
    @Vargas: A reference to a pointer is 'int *&x' and not 'int &*x'. What you mentioned is 'pointer to reference'. By the way, C++ does not allow pointer to reference. – Chubsdad Sep 20 '10 at 02:49
  • 1
    @Chubsdad +1; @Vargas, read from right to left ("x is a reference to a pointer to an int") – Dan Sep 20 '10 at 19:50
1

Just adding: I think your spacing is misleading. Maybe things get a bit clearer if you change it.

The , &, * and so on is part of the type, so keep it with the type:

void foo(int& x) 
void foo(int* x)
void foo(int** x)
void foo(int*& x)

int& is an reference to an int, int* is a pointer to an int, int** is a pointer to an pointer to an int, and so on. You still need to read the types from right to left - int*& being a reference to an pointer to an int. But that's consistent.

I think this is easier to read and represents better what is meant.

foo
  • 1,968
  • 1
  • 23
  • 35