Search code examples
c++functionprototypeampersand

What does a function prototype mean with an ampersand in it?


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?


Solution

  • 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.