Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 312
DCIndieDev Avatar asked Dec 12 '25 21:12

DCIndieDev


2 Answers

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.

like image 160
Jörg Beyer Avatar answered Dec 14 '25 12:12

Jörg Beyer


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

like image 35
tmpearce Avatar answered Dec 14 '25 11:12

tmpearce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!