3

Possible Duplicate:
What does the '&' operator do in C++?

In my CS class today the teacher showed us some examples of functions and templates and some of the prototypes for functions had ampersands in the list of parameters like this:

void exchange( T & x, T & y ) ; // prototype

what does that mean? What should I use it for?

Community
  • 1
  • 1
TestinginProd
  • 1,085
  • 1
  • 15
  • 35
  • 4
    If this was in class, you should have asked your professor! Never be afraid to ask questions. – Andrew Marshall Feb 28 '12 at 20:09
  • 1
    If you were shown a prototype like that in class, the purpose of the lecture was probably to *introduce* ampersands. Pay closer attention next time. – Rob Kennedy Feb 28 '12 at 20:16

2 Answers2

5

the & is for reference. In short that's something like a pointer, that can't be NULL. Wikipedia has something on this topic here.

References are cheap when they are used in function/method calls, since the object doesn't need to be copied in your function call. You still have the same syntax as if you had with a copied object. With pointers you would need to handle the special case, that the pointer is NULL.

That is a usual reason to use them. If I guess right and exchange means something like swap the tow objects x and y, the the cost of the function call is directly related to the cost of coping the object, so saving some copies may be a relevant optimization.

Jörg Beyer
  • 3,631
  • 21
  • 35
1

The & means 'reference to' - x is a reference to a T, not a copy.

tmpearce
  • 12,523
  • 4
  • 42
  • 60